PHP array containing 12 months and start with current month and decrement - php

I'm trying to get an array of 12 months starting with current month, decrement and be like "Mar 2022".
This is my code:
$months = array();
$count = 0;
while ($count <= 11) {
$months[] = date('M Y', strtotime("-".$count." month"));
$count++;
}
But has some problems with months with fewer days.
For example: dd($months[0]) => "Mar 2022" and dd($months[1]) => "Mar 2022" had to be "Feb 2022".

One quick solution will as below:
<?php
$months = array();
$count = 0;
while ($count <= 11) {
$prevMonth = ($count == 1) ? "first day of previous month" : "-$count month";
$months[] = date('M Y', strtotime($prevMonth));
$count++;
}
Refrence: Getting last month's date in php

use carbon.
use Carbon\Carbon;
for ($i = 0; $i < 12; $i++) {
array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
};

Related

How to dynamically increment dates using strtotime?

I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?
<?php
//incrementing dates for bi-weekly (26 periods// 26 dates)
$firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
$i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
echo'<br>';
$seconddate =strtotime("+14 days", strtotime($i));//2
$ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
echo'<br>';
?>
How about this:
// initialize an array with your first date
$dates = array(strtotime("+17 days", strtotime("2017-04-03")));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
// add 14 days to previous date in the array
$dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
echo date("Y-m-d", $date) . PHP_EOL;
}
Probably the easiest way to do this would be with an array
$myDates = [];
$firstdate = strtotime("+17 days", strtotime("2017-04-03"));
array_push($myDates, date("Y-m-d",$firstdate));
for($i=0;$i<25;$i++){
$lastdate = $myDates[$i];
$nextdate = strtotime("+14 days", strtotime($lastdate));
array_push($myDates,date("Y-m-d",$nextdate));
}
echo "<pre>".var_dump($myDates)."</pre>";

php - for loop for each month of year

I want a loop that checks the current month, 12 months in the future and 4 months in the past.
For example: Today is 1st August 08. My loop should go through April, May, June, July, August, September, October, November, December, January, February, March, April, May, June, July, and August.
I have tried strotime but I don't know how I can loop 4 months back and 12 months in the future.
Here is my code
$i = 1;
$month = strtotime('2013-08-01');
while($i <= 12) {
$month_name = date('F', $month);
echo $month_name;
echo "<br>";
$month = strtotime('+1 month', $month);
$i++;
I think Yoshi was almost there with his answer, but using DatePeriod with DateTime is more consistent and makes for more readable code IMHO:-
$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);
foreach($period as $date){
//$date is an instance of \DateTime. I'm just var_dumping it for illustration
var_dump($date);
}
See it working
This can be quite tricky, here's how I would do it:
$month = date("n", "2013-08-01") - 1; // -1 to get 0-11 so we can do modulo
// since you want to go back 4 you can't just do $month - 4, use module trick:
$start_month = $month + 8 % 12;
// +8 % 12 is the same is -4 but without negative value issues
// 2 gives you: 2+8%12 = 10 and not -2
for ($i = 0; $i < 16; $i += 1) {
$cur_month = ($start_month + $i) % 12 + 1; // +1 to get 1-12 range back
$month_name = date('F Y', strtotime($cur_month . " months"));
var_dump(month_name);
}
something like this?:
$start = -4;
$end = 12;
for($i=$start; $i<=$end;$i++) {
$month_name = date('F Y', strtotime("$i months"));
echo $month_name;
echo "<br>";
}
Your code, just slightly modified.
date_default_timezone_set('UTC');
$i = 1;
$month = strtotime('-4 month');
while($i <= 16) {
$month_name = date('F', $month);
echo $month_name;
echo "<br>";
$month = strtotime('+1 month', $month);
$i++;
}
Simplest solution:
for($i=-4; $i<=12; $i++) {
echo date("F",strtotime( ($i > 0) ? "+$i months" : "$i months") )."\n";
}
Explanation:
The loop starts at -4 and goes all the way upto 12 (total 17, including 0). The ternary statement inside strtotime() simply checks if $i is positive, and if it is, a + is inserted so that we'll get the results for strtotime("+1 months") and similar.
Ta-da!
Using DateTime is the easiest and more readable way.
I would do it like this:
$from = new DateTime('-4 month');
$to = new DateTime('+12 month');
while($from < $to){
echo $from->modify('+1 month')->format('F');
}

Getting the weekday for a certain day in the next 6 months

Is it possible to get the weekday of the 21st of the next 6 months in PHP?
For example, say the 21st falls on a Tuesday next month, then I want "Tuesday" to be returned. But I want this for each of the next 6 months. What is the most elegant solution to this?
Something like that will give you the expected result:
// starting date
$date = new DateTime('2012-08-21');
// iterate for 6 months
for ($i = 0; $i < 6 ; $i++) {
echo $date->format('Y-m-d').' : '.$date->format('l') . PHP_EOL;
$date->modify('+1 month');
}
The DatePeriod and DateInterval classes are super-handy for this sort of thing.
$date = DateTime::createFromFormat('d', 21);
$period = new DatePeriod($date, new DateInterval('P1M'), 6, DatePeriod::EXCLUDE_START_DATE);
foreach ($period as $day) {
echo $day->format('M jS => l'), PHP_EOL;
}
Yes:
<?php
$date = new DateTime;
$date->modify("first day of this month");
$date->modify("+20 days"); //21st
echo $date->format("F: l (Y-m-d)") . PHP_EOL;
for ($i = 0; $i < 6; $i++) {
$date->modify("+1 month");
echo $date->format("F: l (Y-m-d)") . PHP_EOL;
}
Untested, but try this:
$date = 21;
$year = 2012;
$month = date('m'); // Get current month
for($i=0;$i<6;$i++)
{
if($month == 13)
{
$year++;
$month=1;
}
$day = date('l',mktime(0,0,0,$month,$date,$year));
echo "$month $date falls on $day<br />\n";
$month++;
}

How to sum time in php?

PHP: How to sum the result of a foreach statement?
Below is my working code. As you will see, I'm trying to count the days in each month and then sum them.
// A function to calculate days in a given month using just the date
function daysInMonths($date)
{
$month = date("m", strtotime($date));
$year = date("Y", strtotime($date));
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
return $num;
}
// A function that places the date of an unknown number of months into an array:
function getNextMonths($date, $numberOfMonths)
{
$timestamp_now = strtotime($date);
$months[] = date('Y-m-d', $timestamp_now);
for($i = 1;$i <= $numberOfMonths; $i++)
{
$months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
}
// counts the days in each month:
$j=0;
foreach ($months as $days)
{
echo "$j:".daysInMonths($days)."<br>";
++$j;
}
print_r($months);
}
getNextMonths('2011-11-1', '4');
Current output:
Array (
[0] => 2011-11-01
[1] => 2011-12-01
[2] => 2012-01-01
[3] => 2012-02-01
[4] => 2012-03-01
)
After counting:
0:30
1:31
2:31
3:29
4:31
This is all correct, I'm just having trouble summing the array after I have the days of the month counted.
$tot = 0;
foreach ($months as $days) {
$tot += daysInMonths(days);
}
echo $tot;
array_sum() - http://php.net/manual/en/function.array-sum.php
$t = array(
31,
28,
31
);
echo array_sum($t); // 90
Add a counter like you use in for while etc!!

PHP- Display days weekly by giving 2 dates

I'd like display dates by week number between giving 2 dates like example below. Is this possible in PHP?
if the dates are 2010-12-01 thru 2010-12-19, it will display it as follows.
week-1
2010-12-01
2010-12-02
2010-12-03
2010-12-04
2010-12-05
2010-12-06
2010-12-07
week-2
2010-12-08
2010-12-09
2010-12-10
2010-12-11
2010-12-12
2010-12-13
2010-12-14
week-3
2010-12-15
2010-12-16
2010-12-17
2010-12-18
2010-12-19
and so on...
I use mysql. It has startdate end enddate fields.
thank you in advance.
I can get how many weeks in those giving 2 dates and display them using a
datediff('ww', '2010-12-01', '2010-12-19', false); I found on the internet.
And I can display dates between two dates as follows. But I am having trouble grouping them by week.
$sdate = "2010-12-01";
$edate = "2010-12-19";
$days = getDaysInBetween($sdate, $edate);
foreach ($days as $val)
{
echo $val;
}
function getDaysInBetween($start, $end) {
// Vars
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start); // Start as time
$eTime = strtotime($end); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
// Get days
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
// Return days
return $days;
}
New answer.
$current_date = strtotime('2010-12-01');
$end_date = strtotime('2010-12-19');
$day_count = 0;
$current_week = null;
do {
if ((int)($day_count / 7) + 1 != $current_week) {
$current_week = (int)($day_count / 7) + 1;
echo 'week-'.$current_week.'<br />';
}
echo date('Y-m-d', $current_date).'<br />';
$current_date = strtotime('+1 day', $current_date);
$day_count ++;
} while ($current_date <= $end_date);
You will definitely need this: Simplest way to increment a date in PHP?. Write a forloop and increment the day every time. You will also need the DateTime class and functions as date. Indeed asking for date('W', yourDateHere) is a nice idea.
You will get something like this (pseudocode)
$startDate;
$endDate;
$nrOfDays = dateDiffInDays($endDate, $startDate);
$currentWeek = date('W',$startDate);
for($i = 0; $i < $nrOfDays; $i++)
{
$newDay = date('+$i day', $startDate); // get the incremented day
$newWeek = date('W', $newDay); // get the week of the new day
if($newWeek != $currentWeek) // check if we must print the new week, or if we are still in the current
print $newWeek;
print $newDay; // print the day
}
Hope this helps. Good luck.
Tools sufficient to do the job:
strtotime('2010-11-23') - to get a timestamp from a date
strtotime('+1 day', $someTimestamp) - to get the next day
date('W', $someTimestamp) - to get the week number (if you want to group by ISO week number)
array_chunk($orderedListOfSuccessiveDates, 7) - to split in groups of seven days (if you don't want to group by ISO week number)
Warning: Never, ever increment days by adding 86400 to the timestamp! That is the easiest way to break everything when Daylight Saving comes along. Either use the strtotime function or the DateTime class.
Here you go. Although this is with weeks starting on sundays (just change it to monday if need be). And it doesnt work if the dates arent in the same year. But it should be pretty easy to fix that. If not_same_year then ...
$start_date = mktime(0, 0, 0, 12, 01, 2010);
$start_date_week_number = (int) date("W", $start_date);
$end_date = mktime(0, 0, 0, 12, 19, 2010);
$end_date_week_number = (int) date("W", $end_date);
$n = $start_date_week_number;
$w = 1;
$date = $start_date;
while($n <= $end_date_week_number) {
echo("<strong>Week " . $w . "</strong><br />");
$s = 0;
$e = 6;
if($n == $start_date_week_number) $s = (int) date("w", $start_date);
elseif($n == $end_date_week_number) $e = (int) date("w", $end_date);
while($s <= $e) {
echo(date("j-m-y", $date) . "<br />");
$c_date = getdate($date);
$date = mktime($c_date['hours'], $c_date['minutes'], $c_date['seconds'], $c_date['mon'], $c_date['mday'] + 1, $c_date['year']);
$s++;
}
$n++; $w++;
}
DEMO HERE
Edit: just fixed it when I realized you wanted to count the weeks (not get the actual week number)...
$startDate = new DateTime('2010-01-01');
$endDate = new DateTime('2010-01-14');
$weeksDays = getWeeksDaysBetween($startDate, $endDate);
foreach($weeksDays as $week => $days)
{
echo "Week $week<ul>";
foreach($days as $day){
echo "<li>$day</li>";
}
echo "</ul>";
}
function getWeeksDaysBetween($startDate, $endDate)
{
$weeksDays = array();
$dateDiff = $endDate->diff($startDate);
$fullDays = $dateDiff->d;
$numWeeks = floor($fullDays / 7) + 1;
$weeksDays[1][] = $startDate->format('Y-m-d');
for ($i = 1; $i <= $fullDays; $i++)
{
$weekNum = floor($i / 7) + 1;
$dateInterval = DateInterval::createFromDateString("1 day");
$weeksDays[$weekNum][] = $startDate->add($dateInterval)->format('Y-m-d');
}
return $weeksDays;
}

Categories