Php如何从一年中的日期到现在,反之亦然

got*_*ch4 12 php date

你如何从一年中的第n天到日期,如:

getdatefromday(275, 2012) 
Run Code Online (Sandbox Code Playgroud)

它输出一个日期(如果一个对象更好).

我也想做相反的事情,比如说 getdayoftheyear("21 oct 2012")

Ste*_*ley 20

这很简单.你应该在阅读了DateTime对象的createFromFormat静态方法在这里,该date功能在这里strtotime功能在这里.

// This should get you a DateTime object from the date and year.
function getDateFromDay($dayOfYear, $year) {
  $date = DateTime::createFromFormat('z Y', strval($dayOfYear) . ' ' . strval($year));
  return $date;
}

// This should get you the day of the year and the year in a string.
date('z Y', strtotime('21 oct 2012'));
Run Code Online (Sandbox Code Playgroud)

  • 由于 [php 5.3.9 with leap days](http://stackoverflow.com/questions/35556275/phps-datetimecreatefromformat-ignores-leap-years) 以来的一个已知错误,您应该反转格式顺序:DateTime::createFromFormat( 'Y z', strval($year) . ' . strval($dayOfYear)); (7认同)

Vyt*_*tas 5

尝试(从几天开始01):

$date = DateTime::createFromFormat( 'Y z' , '2012 275');
var_dump($date);
Run Code Online (Sandbox Code Playgroud)

然后:

echo date('z', strtotime('21 oct 2012'));
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案。使用格式“z Y”会导致在 php 5.4+ 中跳过闰年的错误。“Y z”格式是解决方法。请参阅:https://bugs.php.net/bug.php?id=62476 (2认同)