Timestamp of nearest valid month

◇◆丶佛笑我妖孽 提交于 2020-01-06 08:44:25

问题


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!


回答1:


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?



来源:https://stackoverflow.com/questions/1872812/timestamp-of-nearest-valid-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!