displaying the dates in a particular format php - php

I have a date array sorted in asc order. I want to display the date as
Oct 10,12,24 2012
Dec 12,20,24 2012
Jan 02,10,25 2013
I have got the dates as the month ie.Oct,Dec,Jan.. and the dates and year, but i want it to be displayed in the above mentioned format. I have tried the below code, but it is not giving the desired result. Can someone pls help me with this?
$CruiseDetailsSailing is the array containing the date in an ascending order.
if (count($CruiseDetailsSailing) > 0) {
$date = array();
$month = array();
$Year = array();
for ($n = 0; $n < count($CruiseDetailsSailing); $n++) {
if ($CruiseDetailsSailing[$n] != "") {
$date[] = date('Y-m-d', strtotime($CruiseDetailsSailing[$n]));
}
}
}
sort($date);
if (count($date) > 0) {
$temp = "";
$yeartemp = "";
for ($p = 0; $p < count($date); $p++) {
$month = date("M", strtotime($date[$p]));
$day = date("d", strtotime($date[$p]));
$year = date("Y", strtotime($date[$p]));
if ($month != $temp) {
$temp = $month;
?>
<li> <?php
echo $temp . " " . $day . ", ";
} else {
echo $day . ", ";
}
if (($p != 0) && ((date("M", strtotime($date[$p]))) == (date("M", strtotime($date[$p - 1])))) && ((date("Y", strtotime($date[$p]))) == (date("Y", strtotime($date[$p - 1]))))) {
echo $year;
}
if (($p != 0) && ((date("M", strtotime($date[$p]))) != (date("M", strtotime($date[$p - 1])))) && ((date("Y", strtotime($date[$p]))) != (date("Y", strtotime($date[$p - 1]))))) {
echo $year;
}
}
Oct is the month and 10,12,24 are the months and 2012 is the year. I got the the dates as Oct 10 2012,Oct 12 2012,Oct 24 2012. I just want to display the results as Oct only once and then the dates and the year just once.
Thanks,

this should do:
sort($date); // sorted input array containing dates
$result_dates = Array();
// bring dates in correct format
foreach($date as $current_date) {
$month = date("M", strtotime($current_date));
$day = date("d", strtotime($current_date));
$year = date("Y", strtotime($current_date));
$result_dates[$year][$month][] = $day;
}
// output dates
foreach($result_dates as $year => $months) {
foreach($months as $month => $days) {
echo $month . " " . implode(",", $days) . " " . $year . "\n";
}
}
the following input:
$date = Array('10/03/2012', '10/10/2012', '10/17/2012', '11/04/2012', '11/05/2012', '11/23/2012');
results in:
Oct 03,10,17 2012
Nov 04,05,23 2012

You can do it simply like this
/* Array to pass the function
$date_array = array(
'2012-10-10',
'2012-12-10',
'2012-24-10'
);
*/
function getMyDateFormat($date_array){
$days = array();
$year = '';
$month = '';
sort($date_array);
if(count($date_array)>0){
foreach($date_array as $row)
{
$days[] = date('d',strtotime($row));
$year = date('Y',strtotime($row));
$month = date('M',strtotime($row));
}
$new_date = $month .' '. implode(',',$days) .' '. $year;
return $new_date;
}
}

Related

Custom Month and Year inside php for-loop

I saw this question:
how to get the previous 3 months in php
My question is.. How do i output from a custom month.
I want to start from Mar 2018 (or any M Y user inputs) and it should output the next 3 (or any number user inputs) months.
Ex: Mar, Apr, May
The code below is from current month and year.
// current month: Aug 2018
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month");
echo $dte = date('M Y', $x);
echo '<br>';
}
And the output is
Aug 2018
Sep 2018
Oct 2018
You could use the DateTime class and increment using a DateInterval object:
// Assuming these are the user inputs
$month = 11;
$year = 2015;
// We create a new object with year and month format
$date = DateTime::createFromFormat('Y m', $year . ' ' . $month);
for ($i = 0; $i <= 2; $i++){
// Output the month and year
echo $date->format('m Y') . '<br>';
// Add 1 month to the date
$date->add(new DateInterval('P1M'));
}
Output:
11 2015
12 2015
01 2016
Documentation:
DateTime::createFromFormat
DateTime::format
DateTime::add
Change it to this as below it will give you as expected see the below code
// current month: Aug 2018
$effective_date = "MAR 2018";
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month",strtotime($effective_date));
echo $dte = date('M Y', $x);
echo '<br>';
}
This may be also helpful:
<?php
$month = 11;
$year = 2017;
$count = 15;
for ($i = 1; $i <= $count; $i++) {
$month++;
if ($month > 12) {
$month = 1;
$year++;
}
$x = DateTime::createFromFormat('Y-m', $year.'-'.$month);
echo $x->format('m-Y');
echo '<br>';
}
?>
Output:
12-2017
01-2018
02-2018
03-2018
04-2018
05-2018
06-2018
07-2018
08-2018
09-2018
10-2018
11-2018
12-2018
01-2019
02-2019
Try this code for add nth Days, Months and Years
$n = 2;
for ($i = 0; $i <= $n; $i++){
$d = strtotime("$i days");
$x = strtotime("$i month");
$y = strtotime("$i year");
echo "Dates : ".$dates = date('d M Y', "+$d days");
echo "<br>";
echo "Months : ".$months = date('M Y', "+$x months");
echo '<br>';
echo "Years : ".$years = date('Y', "+$y years");
echo '<br>';
}
You can generate the date with strtotime() function
Check this phpfiddle
<?php
$currMonth = 11;
$currYear = 2017;
$count = 15;
$currentYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $currentYear.'<br>';
for ($i = 1; $i < $count; $i++) {
$currMonth++;
if ($currMonth > 12) {
$currMonth = 1;
$currYear++;
}
$newMonthandYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $newMonthandYear.'<br>';
}
?>
<?php
$year = date('Y');
//start at march
$startMonth = 7;
//go forwards 2 months
$stepForwards = 22;
for ($i = $startMonth; $i <= $stepForwards; $i++){
if($i > 12 ) {
$month = $i % 12 == 0 ? 12 : $i % 12;
}
else {
$month = $i;
}
echo date("M Y", strtotime(date($year.'-'.$month.'-1'))) . "<br/>";
if($month == 12) {
$year++;
echo "<br/>";
}
}

Counting the (year)quarters between two dates

I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.
Here are the quarters(i used numerical representations for the months)
01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter
I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.
I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.
Thanks for your help in advance.
I managed to do this using multiple functions; basically, if this is needed for chart statistics, then a more specific approach might be the case.
I have done this in Laravel with timestamp dates as input (this code can be adapted for getting semesters also :) , it works and is already tested):
public static function getQuartersBetween($start_ts, $end_ts)
{
$quarters = [];
$months_per_year = [];
$years = self::getYearsBetween($start_ts, $end_ts);
$months = self::getMonthsBetween($start_ts, $end_ts);
foreach ($years as $year) {
foreach ($months as $month) {
if ($year->format('Y') == $month->format('Y')) {
$months_per_year[$year->format('Y')][] = $month;
}
}
}
foreach ($months_per_year as $year => $months) {
$january = new Date('01-01-' . $year);
$march = new Date('01-03-' . $year);
$april = new Date('01-04-' . $year);
$june = new Date('01-06-' . $year);
$july = new Date('01-07-' . $year);
$september = new Date('01-09-' . $year);
$october = new Date('01-10-' . $year);
$december = new Date('01-12-' . $year);
if (in_array($january, $months) && in_array($march, $months)) {
$quarter_per_year['label'] = 'T1 / ' . $year;
$quarter_per_year['start_day'] = $january->startOfMonth();
$quarter_per_year['end_day'] = $march->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($april, $months) && in_array($june, $months)) {
$quarter_per_year['label'] = 'T2 / ' . $year;
$quarter_per_year['start_day'] = $april->startOfMonth();
$quarter_per_year['end_day'] = $june->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($july, $months) && in_array($september, $months)) {
$quarter_per_year['label'] = 'T3 / ' . $year;
$quarter_per_year['start_day'] = $july->startOfMonth();
$quarter_per_year['end_day'] = $september->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($october, $months) && in_array($december, $months)) {
$quarter_per_year['label'] = 'T4 / ' . $year;
$quarter_per_year['start_day'] = $october->startOfMonth();
$quarter_per_year['end_day'] = $december->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
}
return $quarters;
}
and getting the years between:
public static function getYearsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current < $end_ts) {
$temp_date = $current;
$year = new Date($temp_date);
$return_data[] = $year;
$current = strtotime("+1 year", $current); // add a year
}
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
, also getting the months needed
public static function getMonthsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = $month_list = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current <= $end_ts) {
$temp_date = $current;
$date = new Date($temp_date);
$month_list[] = $date;
$current = strtotime("+1 month", $current); // add a month
}
$start_date_last_month = new Date(array_first($month_list));
$start_date_last_month = $start_date_last_month->startOfMonth()->format('m-d');
$temp_end_date = new Date($start_ts);
$temp_end_date = $temp_end_date->format('m-d');
if ($start_date_last_month < $temp_end_date) {
array_shift($month_list);
}
$end_date_last_month = new Date(end($month_list));
$current_day_month = $end_date_last_month->endOfMonth()->format('m-d');
$temp_end_date = new Date($end_ts);
$end_day_of_month = $temp_end_date->format('m-d');
if ($end_day_of_month < $current_day_month) {
array_pop($month_list);
}
if (count($month_list) == 0) {
$month_list[] = $end_date_last_month->subMonth();
}
$return_data = $month_list;
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
You can do something like in this example:
$February = 2;
$October = 10;
$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:
$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
You´re description is not very clear, let me know if that´s what you had in mind.
Not sure if the following is what you are meaning but might be useful
$date_start='2015/03/12';
$date_end='2017/11/14';
$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );
$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );
printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );
/*
This will output
----------------
Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
Something like this in the function and you should be set.
use Carbon\Carbon;
$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param
$fY = $first->year; //2012
$fQ = $first->quarter; //1
$sY = $second->year; //2014
$sQ = $second->quarter; //3
$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year
for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
$s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
for ($q=$s; $q <= 4; $q++) { //for each quarter
$n++; //count it
}
}
if ($sY > $fY) { //if both dates are not in the same year
$n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
$n++; //count it
}
}
print $n; //the value to return (11)

Count number of Sunday's in given Month and year

I want output to be count of sunday's present in given month and year.
This is my code:
$months=$_POST['month'];
$years=$_POST['year'];
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
I am not getting any output if i echo $num_sundays. Please help me . I am new to PHP
You just need to remove <br> from these two lines:
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
Otherwise this will be the part of start and end date, and your strtotime() will return false.
Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return false for both.
Example 2:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return the values
Complete Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
echo "Total Count is: ".$num_sundays;
?>
DEMO: This will return 4 sunday
Without loop. I hope this gives the correct results.
date_default_timezone_set('UTC');
// unix timestamp 0 = Thursday, 01-Jan-70 00:00:00 UTC
// unix timestamp 259200 = Sunday, 04-Jan-70 00:00:00 UTC
$sun_first = strtotime('1970-01-04');
$t1 = strtotime('2018-10-01') - $sun_first - 86400;
$t2 = strtotime('2018-10-31') - $sun_first;
$sun_count = floor($t2 / 604800) - floor($t1 / 604800); // total Sunday from 2018-10-01 to 2018-10-31
echo $sun_count; // 4
Get all sunday in month see below code:
function total_sun($month,$year)
{
$sundays=0;
$total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year);
for($i=1;$i<=$total_days;$i++)
if(date('N',strtotime($year.'-'.$month.'-'.$i))==7)
$sundays++;
return $sundays;
}
echo total_sun(11,2016);
http://phpio.net/s/l9f
Check following Example. I work perfectly..
function dayCount($day,$month,$year){
$totalDay=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$count=0;
for($i=1;$totalDay>=$i;$i++){
if( date('l', strtotime($year.'-'.$month.'-'.$i))==ucwords($day)){
$count++;
}
}
echo $count;
}
dayCount('saturday',3,2019);
working example dorcode calculation
$startd="31-7-2006 15:30:00";
$endd="31-7-2007 15:30:00";
$startDate=$startd;
$endDate=$endd;
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
if($startDate1>$endDate1)
{
$startDate1 = strtotime($endDate);
$endDate1 = strtotime($startDate);
} else {
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
}
$p=0;
for($i = strtotime("Sunday", $startDate1); $i <= $endDate1;
$i =strtotime('+1 week', $i))
{
$p++;
echo $p.": ".date('F d, Y', $i)."<br>";
}
To get a count of any given day in a given month in a year:
$year = '2019';
$month = '2';
$day = 'Tuesday';
$count = 0;
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$date = new Datetime($year.'-'.$month.'-01');
for($i=1; $i<$days; $i++){
if($date->format('l') == $day){
$count++;
}
$date->modify('+1 day');
}
echo "Count: $count";
Use this code if it helps you
public function countWeekendDays($month, $year){
$daytime = strtotime(date($year."/".$month."/01 00:00:01"));
$daysOfMonth = date("t", $daytime);
$weekdays = 0;
for ($day=1; $day <= $daysOfMonth; $day++) {
$time = strtotime(date($year.'/'.$month.'/'.$day.' 00:00:01'));
$dayStr = date('l', $time);
if ($dayStr == 'Saturday' || $dayStr == 'Sunday') {
$weekdays++;
}
}
return $weekdays;
}
Simple code for day count:
function dayCount($day,$month,$year){
$totaldays = date('t',strtotime($year.'-'.$month.'-01'));
$countday = 4;
if(($totaldays - $day) >= 28 ){
$countday = 5;
}
return $countday;
}
echo dayCount(1,9,2019);
$day =Carbon\Carbon::now("Asia/Kolkata")->daysInMonth;
echo $day.'</br>';
if($day = 28) {
$weekend = 8;
}elseif($day = 29) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if($first_day_saturday || $first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}elseif($day = 30) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}else {
$first_day_thrusday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isThursday();
$first_day_friday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isFriday();
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_friday || $first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday || $first_day_thrusday) {
$weekend = 9;
}else {
$weekend = 8;
}
}
echo $weekend.'</br>';

Get the same specific date on each month of the whole year

I am working on a "cut-off" date and I need to set it on every month. Say, I set the cut-off date to August 25 for this year, then it should be September 25, October 25 and so on till the year ends.
Here's the code I have:
$now = "2015-08-25";
$nextDate = getCutoffDate($now);
echo $nextDate;
function getCutoffDate($start_date)
{
$date_array = explode("-",$start_date); // split the array
// var_dump($date_array);
$year = $date_array[0];
$month = $date_array[1];
$day = $date_array[2];
/*if (date('n', $now)==12)
{
return date("Y-m-d",strtotime(date("Y-m-d", $start_date) . "+1 month"));
}*/
if (date("d") <= $day) {
$billMonth = date_format(date_create(), 'm');
}
else{
$billMonth = date_format(date_modify(date_create(), 'first day of next month'), 'm');
}
// echo date("d").' '. $billMonth.'<br>';
$billMonthDays = cal_days_in_month(CAL_GREGORIAN, ($billMonth), date("Y"));
// echo $billMonthDays.'<br>';
if ($billMonthDays > $day) {
$billDay = $day;
} else {
$billDay = $billMonthDays;
}
}
I got this from here: http://www.midwesternmac.com/blogs/jeff-geerling/php-calculating-monthly
It returns the same date for the next month only, but how do I get the specific date of EACH month of the current year? Kindly leave your thoughts. Still a newbie here, sorry.
In that case, this should be enough:
<?php
for($i=8; $i<=12; $i++) {
echo sprintf('25-%02d-2015', $i) . '<br>';
}
but if you need more flexible way:
<?php
$date = new DateTime('25-08-2015');
function getCutoffDate($date) {
$days = cal_days_in_month(CAL_GREGORIAN, $date->format('n'), $date->format('Y'));
$date->add(new DateInterval('P' . $days .'D'));
return $date;
}
for($i = 0; $i < 5; $i++) {
$date = getCutoffDate($date);
echo $date->format('d-m-Y') . '<br>';
}
This should print:
25-09-2015
25-10-2015
25-11-2015
25-12-2015
25-01-2016

Listing timestamp month/year as blog archive in PHP

Assuming I have multiple timestamps of multiple years and months in an array of timestamps (eg 123456, 111222333, 2112321321, 232234422, 1111343222, 231111211, etc), I want to sort them into this format:
2012
06
09
2004
03
08
2003
01
02
Is there any way of doing this? I am using PHP
You can do this.
See if this gets you started; it's incomplete but takes care of most of it. Just a few additions and it should work how you want.
<?php
$timestamps = array();
for ($i = 0; $i < 100; ++$i) {
$ts = mktime(rand(0, 23), rand(0, 59), rand(0, 59), rand(1, 12), rand(1, 31), rand(2000, 2012));
$timestamps[] = $ts;
}
sort($timestamps);
$lastYear = null;
echo "<ul>\n";
foreach($timestamps as $ts) {
$year = date('Y', $ts);
if ($year != $lastYear) {
if ($lastYear != null) {
echo "</ul>\n";
}
$lastYear = $year;
echo "<li>$year<ul>\n";
}
echo "<li>" . date('m-d', $ts) . "</li>\n";
}
echo "</ul></ul>";
I create an array of 100 random timestamps to populate the list at the beginning.
I've found a solution:
foreach($timestamps as $time){
$year = date('Y', $time);
$month = date('m', $time);
if(!$ts_arr[$year]){
$ts_arr[$year] = array();
}
array_push($ts_arr[$year], $month);
$ts_arr[$year] = array_unique($ts_arr[$year]);
}
It's not perfect, but it works!

Categories