Timestamp of nearest valid month

2019-08-17 14:22发布

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!

标签: php date time
1条回答
叼着烟拽天下
2楼-- · 2019-08-17 15:25

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?

查看更多
登录 后发表回答