tags:

views:

63

answers:

1

Just a quickie.. How to derive the unixtime of nearest March or June?

If the current month is February of 2009, the script should give the unixtime of March 01, 2009.

If the current month is April of 2009, the script should give the unixtime of June 01, 2009.

If the current month is October of 2009, the script should give the unixtime of March 01, 2010.

Thank you for any help!

+5  A: 

Update: Sorry, my bad. "next" works with days and in cases like "next month" but not "next March" so it's a little more convoluted than the original one liner.

strtotime() is really awesome for things like this:

$tests = array(
  strtotime('2 february'),
  strtotime('4 april'),
  strtotime('9 november'),
);

foreach ($tests as $test) {
  echo date('r', $test) . ' => ' . date('r', nextmj($test)) . "\n";
}

function nextmj($time = time()) {
  $march = strtotime('1 march', $time);
  $june = strtotime('1 june', $time);
  if ($march >= $time) {
    return $march;
  } else if ($june >= $time) {
    return $june;
  } else {
    return strtotime('+1 year', $march);
  }
}

Output:

Mon, 02 Feb 2009 00:00:00 +0000 => Sun, 01 Mar 2009 00:00:00 +0000
Sat, 04 Apr 2009 00:00:00 +0000 => Mon, 01 Jun 2009 00:00:00 +0000
Mon, 09 Nov 2009 00:00:00 +0000 => Mon, 01 Mar 2010 00:00:00 +0000

Also see What date formats does the PHP function strtotime() support?

cletus
That is exactly I was looking for! Thumbs up for the one liner!
Nirmal
Oops.. But strtotime('next march') kind of thing is not working and not even throwing any error.
Nirmal
Hah, that solved the whole query! Thanks.
Nirmal