簡體   English   中英

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

[英]Php how to go from day of the year to date and vice versa

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

getdatefromday(275, 2012) 

它輸出一個日期(如果一個對象更好)。

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

這很簡單。 你應該在閱讀了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'));

嘗試(從0開始的日期不是1 ):

$date = DateTime::createFromFormat( 'Y z' , '2012 275');
var_dump($date);

然后:

echo date('z', strtotime('21 oct 2012'));
$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),它實際上知道第一個月的第32天是2dn月的第一天,依此類推。

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'));
}

您可以使用strtotime()來獲取年份值的秒數( http://de2.php.net/manual/en/function.strtotime.php )。 比天數(秒* 24 * 60 * 60)。 現在你可以將這個值與date()一起使用(參見第一個答案)

一年中的一天很容易。 只需使用日期函數和手冊中記錄的正確參數(它在1月1日返回0,在閏年時為12月31日返回365)。

走另一條路需要一點創造力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM