0

I am using this function:

date("Y-m-d", strtotime("-1 week"));

What I am wandering is if I use this function this way will it jump the month of Feb.?

The reason I am asking is because I know that if you do this:

date("m/Y",strtotime("-1 months"));

Like in this example: PHP date() and strtotime() return wrong months on 31st

It will jump the month of Feb.

Community
  • 1
  • 1
jnbdz
  • 4,863
  • 9
  • 51
  • 93
  • 2
    Did you try it? That will tell you the answer. – John Conde Dec 03 '13 at 19:45
  • I am not sure how. Because I don't know if I add to it "-10 months" to strtotime() if it will affect the result in some way. Any suggestions? – jnbdz Dec 03 '13 at 19:47
  • I doubt that offsetting a *week* will jump a *month*. – user2864740 Dec 03 '13 at 19:56
  • Me either. But it is better to be careful than having to go back to the code in 2 months to debug. And looking like a fool. – jnbdz Dec 03 '13 at 19:59
  • adding/subbing months is dangerous anyways. `Jan 30 + 1 month` should be what... 'Feb 28'? Because that's the last day of the next month? Or March 2nd, because Feb 30th = Mar 2nd in non-leapyears? – Marc B Dec 03 '13 at 21:23

1 Answers1

2

Try this. (PHP object-oriented format.)

<?php

$d = new DateTime;
$interval = new DateInterval('P1W');
for ($i = 25; $i < 60; $i++)
{
    $d->setDate(2014, 2, $i);
    echo $d->format('Y-m-d'), "  ";

    $d->sub($interval);
    echo $d->format('Y-m-d'), PHP_EOL;  
}

There's nothing ambiguous about the number of days you mean when you say 1 week. When I say 1 week, I always means 7 days. But the term 1 month is fuzzy. I might mean 28, 29, 30, or 31 days. (Change "P1W" to "P1M" in the code above, and run it again. Look at the last four lines in the result.

Also note that the php documentation for strtotime() says, "Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2."

Also see this warning: Example #3 Beware when subtracting months

Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185