我通常搞砸了,但我試圖從一個變量得到一年$date = 2011-01-01
我想從變量得到2011
......我試過這個,但它沒有迴應任何東西。 ..PHP從變量得到年
date(strtotime("Y"), strtotime($date));
我通常搞砸了,但我試圖從一個變量得到一年$date = 2011-01-01
我想從變量得到2011
......我試過這個,但它沒有迴應任何東西。 ..PHP從變量得到年
date(strtotime("Y"), strtotime($date));
$year = date('Y', strtotime('2011-01-01'));
或者,如果你不想轉換爲日期,並相信您的輸入格式:
$year = explode('-', '2011-01-01')[0];
以上需要PHP 5.4,在舊版本中,你需要兩行:
$year = substr($date, 0, 4);
:
$arr = explode('-', '2011-01-01');
$year = $arr[0];
或者然而,這稍微快一些可替代的tigrang建議
或者,更快的方式,因爲salathe建議:
$year = (int) $date;
(一切的第一個破折號會被忽略後,所以$year
將包含日期的年份部分的整數(不像其他的選項,其中$year
將是一個字符串)。
date('Y', strtotime($date))
應該做
第一個參數是格式,二是時間戳。
可能我建議使用PHP的DateTime class作爲一種替代方案:
$date = '2011-01-01';
$dateTime = new DateTime($date);
echo $dateTime->format('Y');
DateTime
是一切都很好,但讓我們去老同學。
sscanf($date, '%d', $year);
// or
$year = strtok($date, '-');
// or
$year = substr($date, 0, 4);
// or
$year = (int) $date;
或,把帽子懂事回,你可以使用DateTime
或正確使用date()
。
$datetime = new DateTime($date);
$year = $datetime->format('Y');
// or
$year = date('Y', strtotime($date));
您可以將日期分解爲列表並單獨調用每個日期項目。
$date = '2012-01-01';
list($year, $month, $day) = explode('-', $date);
echo $year; // echoes 2012
或'$ =一年SUBSTR($日期,0,4);'是sliiiightly更快;) – tigrang
@tigrang感謝,補充說答案了。 – bfavaretto
或'$ year =(int)$ date;'being * waaaaaaaay *更快(對於微小的* way *值) – salathe