2010-08-31 22 views
13

獲得的年,月,日鑑於以下TIMESTRING:PHP - 如何從時間字符串

$str = '2000-11-29'; 

$php_date = getdate($str); 
echo '<pre>'; 
print_r ($php_date); 
echo '</pre>'; 

如何獲得年/月/日在PHP?

[seconds] => 20 
[minutes] => 33 
[hours] => 18 
[mday] => 31 
[wday] => 3 
[mon] => 12 
[year] => 1969 
[yday] => 364 
[weekday] => Wednesday 
[month] => December 
[0] => 2000 

我不知道爲什麼我一年拿到1969。

謝謝

回答

25

您可以使用strtotime解析時間字符串,並通過所產生的時間戳getdate(或使用date格式化你的時間)。

$str = '2000-11-29'; 

if (($timestamp = strtotime($str)) !== false) 
{ 
    $php_date = getdate($timestamp); 
    // or if you want to output a date in year/month/day format: 
    $date = date("Y/m/d", $timestamp); // see the date manual page for format options  
} 
else 
{ 
    echo 'invalid timestamp!'; 
} 

注意strtotime將返回false如果時間字符串無效或無法解析。當你試圖解析的時間戳無效時,你最終會遇到你以前遇到的1969-12-31的日期。

+0

非常感謝您 – q0987 2010-08-31 03:57:17

8

更新:忘了,在第一行的末尾添加分號,試試這個:

<?php  
$str = "2010-08-29"; // Missed semicolon here 
$time = strtotime($str); 

// You can now use date() functions with $time, like 
$weekday = date("l", $time); // Wednesday or whatever date it is  
?> 

希望這將讓你去!

1

使用面向對象的編程風格,你可以用DateTime class

$dateFormat = 'Y-m-d'; 
$stringDate = '2000-11-29'; 
$date = DateTime::createFromFormat($dateFormat, $stringDate); 

這樣做,那麼,你可以使用format()方法

$year = $date->format('Y'); // returns a string 

如果你更喜歡分解你的約會數字格式,而不是字符串格式,您可以使用intval()功能

$year = intval($date->format('Y')); // returns an integer 

這裏是一些格式,你可以用一年的

  • Y一個完整的數字表示,4位年份
  • m月,2個數字有前導零
  • d本月中的某天,2位數字帶前導零
  • H 24小時制一小時,2位數s的前導零
  • i分鐘,2位有前導零
  • s秒,2個數字有前導零

這裏的格式的完整列表,您可以使用:http://php.net/manual/en/function.date.php

3

PHP - 如何從時間字符串獲得年,月,日字符串

$dateValue = strtotime($q);      

$yr = date("Y", $dateValue) ." "; 
$mon = date("m", $dateValue)." "; 
$date = date("d", $dateValue); 
+1

其代碼實踐解釋答案也可以讓未來的讀者受益 – 2015-11-06 10:35:46