【发布时间】:2022-01-24 11:43:55
【问题描述】:
你如何从一年中的第n天到日期像这样进入php:
getdatefromday(275, 2012)
它会输出一个日期(如果是对象则更好)。
我也想做相反的事情,比如getdayoftheyear("21 oct 2012")
【问题讨论】:
你如何从一年中的第n天到日期像这样进入php:
getdatefromday(275, 2012)
它会输出一个日期(如果是对象则更好)。
我也想做相反的事情,比如getdayoftheyear("21 oct 2012")
【问题讨论】:
这很容易。您应该阅读DateTime 对象的createFromFormat 静态方法here、date 函数here 和strtotime 函数here。
// This should get you a DateTime object from the date and year.
function getDateFromDay($year, $dayOfYear) {
$date = DateTime::createFromFormat('z Y', strval($year) . ' ' . strval($dayOfYear));
return $date;
}
// This should get you the day of the year and the year in a string.
date('z Y', strtotime('21 oct 2012'));
【讨论】:
尝试(天数从0 不是1 开始):
$date = DateTime::createFromFormat( 'Y z' , '2012 275');
var_dump($date);
还有:
echo date('z', strtotime('21 oct 2012'));
【讨论】:
'z Y' 格式会导致在 php 5.4+ 中跳过闰年的错误。 'Y z' 格式是解决方法。见:bugs.php.net/bug.php?id=62476
$todayid = date("z"); // to get today's day of year
function dayofyear2date( $tDay, $tFormat = 'd-m-Y' ) {
$day = intval( $tDay );
$day = ( $day == 0 ) ? $day : $day - 1;
$offset = intval( intval( $tDay ) * 86400 );
$str = date( $tFormat, strtotime( 'Jan 1, ' . date( 'Y' ) ) + $offset );
return( $str );
}
echo dayofyear2date($todayid);
一年中的一天
【讨论】:
我知道它有点老了,答案已经被接受,但我想在这里提出另一种方法,尝试使用问题所有者要求的确切格式:
// This gets the day of the year number
// given a formatted date string like
// "21 oct 2012"
function getdayoftheyear($dateString) {
date('z', strtotime($dateString));
}
反过来:
// This gets the date formatted in $dateFormat way
// like "Y-m-d"
// given the $dayOfTheYear and the $year in numeric form
function getdatefromday($dateFormat, $dayOfTheYear, $year) {
date($dateFormat, mktime(0, 0, 0, 1, ($dayOfTheYear + 1), $year));
}
第二个函数使用 mktime() 的一个特性,允许在参数列表中设置任何数字,因为它管理溢出,它自己找到正确的月份。 因此,如果您调用 mktime(0, 0, 0, 1, 32, 2015) 它实际上知道第 1 个月的第 32 天是第 2 个月的第 1 天,依此类推。
【讨论】:
您可以使用 strtotime() 获取年份值的秒数 (http://de2.php.net/manual/en/function.strtotime.php)。比以秒为单位的天数(天 * 24 * 60 * 60)。现在您可以将此值与 date() 一起使用(请参阅第一个答案)
【讨论】:
function DayToTimestamp($day, $year = null)
{
isset($year) or $year = date('Y');
return strtotime("1 Jan $year +$day day");
}
【讨论】:
function getDateFromDayOfYear($dayOfYear,$year){
return date('Y-m-d', strtotime('January 1st '.$year.' +'.$dayOfYear.' days'));
}
【讨论】:
获取一年中的某一天很容易。只需使用带有正确参数的日期函数作为documented in the manual(它在闰年的一月1 日返回0 到十二月31 日的365)。
走另一条路需要一点创造力。
【讨论】: