Jump to content

[SOLVED] strtotime skipping months


arsnova

Recommended Posts

I'm trying to create a consecutive listing of months, but the output skips months in a regular pattern: 2, 0, 1, 2, 0. Instead of

 

2009-10

2009-11

2009-12

2010-01

[...]

 

The result is

 

2009-10

2009-12

2009-12

2009-01

2009-03

2009-03

2009-05

[...]

 

My code:

 

<?php
$now = '2009-10';
for($count = 0; $count <= 12; $count++){
$new_date = strtotime($now . "+$count month");
echo date('Y-m', $new_date).'<br />';
}
?>

 

I'm stumped and really could use some help telling me what I'm doing wrong. Thank you!

Link to comment
https://forums.phpfreaks.com/topic/172609-solved-strtotime-skipping-months/
Share on other sites

That's because $now is not a complete date and strtotime() uses the current date for the part you did not provide and since not every month has 31 days (todays day number) it is going to the next month.

 

Set $now to a day that exists in every month -

 

$now = '2009-10-01';

Thank you very much! As you already know, that did the trick.

 

Probably not the most graceful, but in case it's useful to anyone else, here's my adjusted code:

 

<?php
$now = date("Y-m-01");
for($count = 0; $count <= 12; $count++){
   $new_date = strtotime(date("Y-m-d", strtotime($now)) . "+$count month");
   echo date("m", $new_date).'<br />';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.