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');
}
Related
EDITED directly to the problem :
The code :
<?php
$date = new DateTime('2000-01-31'); // or whatever
for ($i = 0; $i < 100; $i++) {
$currentDay = $date->format('d');
if ($currentDay < $date->format('t')) {
$date->modify('+1 month');
if ($date->format('d') < $currentDay) {
$date->modify('last day of previous month');
}
} else {
$date->modify('last day of next month');
}
echo $date->format('Y-m-d') . "<br>";
}
So, if starting date is 2000-01-31, it works fine. That's just because 31 is the last day of january, so, any other month it will put the last date of the month.
But, if u change starting date to 2000-01-30, it's broken. That's because 30 january is not the last day in january. But anyway, 30 january is greater than days in february, so it transform date to 28/29 february. Since 28/29 february is the last day in february, it proceed the code like when this date == number of days in the month, and on the next iteration instead of putting 30 march, it puts 'last day of next month' (31 of march).
And that's not the unique case. Same thing if u put starting date for example 30-08-2000. 30 is not the last day of august, so it change the date to 30 of september, 30 september is the last day of the september, so it change the date to 31 of octomber, but it's not what I expect.
If I've understood your question correctly then this should be what you're after:
$date = new DateTime('2000-01-31'); // or whatever
$day = $date->format('d');
$date->setDate($date->format('Y'), $date->format('m'), 1);
for ($i = 0; $i < 100; $i++) {
$date->modify('+1 month');
echo echo $date->format('t') < $day ? $date->format('Y-m-t') : $date->format('Y-m-' . $day);
echo '<br />';
}
Hope this helps!
Do I understand correctly that
you want to print the same day for all following months
in case it's higher than the maximum days in the month, last day of that month should be used instead
If yes, this could work:
<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
for ($i = 0; $i < 100; $i++) {
echo $date->format('Y-m-d') . "<br>";
if ($month++ == 12) {
$year++;
$month = 1;
}
$date->modify("${year}-${month}-1");
if ($expectedDay > $date->format('t')) {
$day = $date->format('t');
} else {
$day = $expectedDay;
}
$date->modify("${year}-${month}-${day}");
}
I'd like to work with PHP DateInterval to iterate through months:
$from = new DateTime();
$from->setDate(2014, 1, 31);
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
I'd expect it to returns 31 January, 28 February (as the DateInterval is 1 month), but it actually returns 31 January, 3 March, 3 of April... hence skipping February.
Is there any way to do this simply?
Thanks!
EDIT : as a refernece, here is a solution that seems to cover most use cases:
$date = new DateTime('2014-01-31');
$start = $date->format('n');
for ($i = 0; $i < 28; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > ($start % 12) && $start !== 12) {
$current->modify('last day of last month');
}
$start++;
echo $current->format('Y-m-d').PHP_EOL;
}
You can use DateTime::modify():
$date = new DateTime('last day of january');
echo $date->format('Y-m-d').PHP_EOL;
for ($i = 1; $i < 12; $i++) {
$date->modify('last day of next month');
echo $date->format('Y-m-d').PHP_EOL;
}
EDIT: I think I didn't understand your question clearly. Here is a new version:
$date = new DateTime('2014-01-31');
for ($i = 0; $i < 12; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > $i + 1) {
$current->modify('last day of last month');
}
echo $current->format('Y-m-d').PHP_EOL;
}
The issue is cause by the variance between the last day in each of the months within the range. ie. February ending on 28 instead of 31 and the addition of 1 month from the last day 2014-01-31 + 1 month = 2014-03-03 https://3v4l.org/Y42QJ
To resolve the issue with DatePeriod and simplify it a bit, adjust the initial date by resetting the specified date to the first day of the specified month, by using first day of this month.
Then during iteration, you can modify the date period date by using last day of this month to retrieve the bounds of the currently iterated month.
Example: https://3v4l.org/889mB
$from = new DateTime('2014-01-31');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
echo $date->modify('last day of this month')->format('Y-m-d');
}
Result:
2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31
2015-01-31
Then to expand on this approach, in order to retrieve the desired day from the specified date, such as the 29th. You can extract the specified day and adjust the currently iterated month as needed when the day is out of bounds for that month.
Example: https://3v4l.org/SlEJc
$from = new DateTime('2014-01-29');
$day = $from->format('j');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
$lastDay = clone $date;
$lastDay->modify('last day of this month');
$date->setDate($date->format('Y'), $date->format('n'), $day);
if ($date > $lastDay) {
$date = $lastDay;
}
echo $date->format('Y-m-d');
}
Result:
2014-01-29
2014-02-28 #notice the last day of february is used
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
2014-08-29
2014-09-29
2014-10-29
2014-11-29
2014-12-29
2015-01-29
You may try like this:
$date = new DateTime();
$lastDayOfMonth = $date->modify(
sprintf('+%d days', $date->format('t') - $date->format('j'))
);
I would do it probably like this
$max = array (
31,28,31,30,31,30,31,31,30,31,30,31
); //days in month
$month = 1;
$year = 2014;
$day = 31;
$iterate = 12;
$dates = array();
for ($i = 0;$i < $iterate;$i++) {
$tmp_month = ($month + $i) % 12;
$tmp_year = $year + floor($month+$i)/12;
$tmp_day = min($day, $max[$tmp_month]);
$tmp = new DateTime();
$tmp->setDate($tmp_year, $tmp_month + 1, $tmp_day);
$dates[] = $tmp;
}
var_dump($dates);
This keeps to the same day each month if possible
I have a problem,
$fridays = array();
$fridays[0] = date('Y-m-d', strtotime('first friday of this month'));
$fridays[1] = date('Y-m-d', strtotime('second friday of this month'));
$fridays[2] = date('Y-m-d', strtotime('third friday of this month'));
$fridays[3] = date('Y-m-d', strtotime('fourth friday of this month'));
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));
but there is no fifth friday. Some months have fifth fridays. How to check and not set the last item array?
$fifth = strtotime('fifth friday of this month');
if (date('m') === date('m', $fifth)) {
$fridays[4] = date('Y-m-d', $fifth);
}
You can do this using the PHP date function. Get the month you want in $timestamp and then do something like this:
<?php
function fridays_get($month, $stop_if_today = true) {
$timestamp_now = time();
for($a = 1; $a < 32; $a++) {
$day = strlen($a) == 1 ? "0".$a : $a;
$timestamp = strtotime($month . "-$day");
$day_code = date("w", $timestamp);
if($timestamp > $timestamp_now)
break;
if($day_code == 5)
#$fridays++;
}
return $fridays;
}
echo fridays_get('2011-02');
You can find a similar post about this: In PHP, how to know how many mondays have passed in this month uptil today?
I have a function to count fridays in a month to my very own application.... it could be helpful for someone.
function countFridays($month,$year){
$ts=strtotime('first friday of '.$year.'-'.$month.'-01');
$ls=strtotime('last day of '.$year.'-'.$month.'-01');
$fridays=array(date('Y-m-d', $ts));
while(($ts=strtotime('+1 week', $ts))<=$ls){
$fridays[]=date('Y-m-d', $ts);
}return $fridays;
}
I'm not on a machine that I could test this but what about something along the lines of....
if(date('Y-m-d', strtotime('fifth friday of this month')) > ""){
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));
}
The link below does exactly the same thing and will cover exactly what you are wanting todo without clunky if statements like above..
VERY Similar reading: read more...
the month will have 5 fridays only if it has 30 days and first friday is 1st or 2nd day of the month or if it has 31 days and the first friday is 1st, 2nd or 3rd day of the month, so you can make conditional statement based on this calculation for 5th friday
for($i=0;$i<=5;$i++)
{
echo date("d/m/y", strtotime('+'.$i.' week friday september 2012'));
}
I used this as the basis for my own solution:
$fridays = array();
$fridays[0] = date('d',strtotime('first fri of this month'));
$fridays[1] = $fridays[0] + 7;
$fridays[2] = $fridays[0] + 14;
$fridays[3] = $fridays[0] + 21;
$fridays['last'] = date('d',strtotime('last fri of this month'));
if($fridays[3] == $fridays['last']){
unset($fridays['last']);
}
else {
$fridays[4] = $fridays['last'];
unset($fridays['last']);
}
print_r($fridays);
I needed to get an array of every Friday in a month, even if there were 5 and this seemed to do the trick using the original question as my basis.
<?php //php 7.0.8
$offDays = array();
$date = date('2020-02');
$day= 'Friday';
$offDays[0] = date('d',strtotime("first {$day} of ".$date));
$offDays[1] = $offDays[0] + 7;
$offDays[2] = $offDays[0] + 14;
$offDays[3] = $offDays[0] + 21;
$offDays['last'] = date('d',strtotime("last {$day} of ".$date));
if($offDays[3] == $offDays['last']){
unset($offDays['last']);
}
else {
$offDays[4] = $offDays['last'];
unset($offDays['last']);
}
foreach($offDays as $off){
echo date('Y-m-d-D',strtotime(date($date."-".$off)));
echo "\n";
}
?>
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++;
}
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;
}