2017-02-16 31 views

回答

1

讓我們假設你有一個名爲$date

變量字符串
$date = '2017-01-20'; 

可以explode它變成一個list如果您確定的格式是一致的:

list($year, $month, $day) = explode("-", $date, 3); 

您可以將日期轉換爲使用strtotime在其他功能使用像date時間整數。這具有能夠測試,這是一個結構良好的日期額外的好處:

$time = strtotime($date); 
if ($time === false) die("Bad date format: $date."); 
$year = date('Y', $time); 
$month = date('m', $time); // 'n' if you don't want leading zero 
$day = date('d', $time); // 'j' if you don't want leading zero 

由於jasonmoqio指出,既然你問了速度最快,substr是一點點比爆炸更快。 (在我的工作站上,循環substr與爆炸1000萬次相比爆炸只產生了千分之一秒的改善,所以除非這個循環運行數百萬次,否則你不會注意到它的差異,應該選擇。代碼的可讀性)

$year = substr($date, 0, 4); 
$month = substr($date, 5, 2); 
$day = substr($date, 8, 2); 
+0

你的工作,但它比'substr'慢慢 – jasonmoqio

1

好吧,如果你知道輸出將始終是其格式爲「YYYY-MM-DD」的字符串,最基本的做法是:

<?php 

    $query = ... //query is your string "YYYY-MM-DD" 
    $year = substr($query, 0, 4); 
    $month = substr($query, 5, 2); 
    $day = substr($query, 8, 2); 

    echo $month; 
    echo $day; 
    echo $year; 
?> 
+0

substr的第三個參數是長度,而不是位置。所以第一個應該是'$ year = substr($ date,0,4);'等等。 – redreinard

+0

我很抱歉這門語言搞砸了。我的回答已被編輯。謝謝! –

+0

抱歉再次發生錯誤,但月份和日期需要長度爲2,長度不是基於0的。 – redreinard

0

試試這個:

$date = new DateTime('2017-01-20'); 
echo 'Year:'.$date->format("Y"); 
echo 'Month:'.$date->format("m"); 
echo 'Day:'.$date->format("d"); 

輸出:

Year: 2017 
Month: 01 
Day: 20 
0

如果你想快速從MySQL獲得的日期,請嘗試使用正則表達式是這樣的。

if (preg_match('/^(?P<year>\d+)[-\/](?P<month>\d+)[-\/](?P<day>\d+)$/', $your_date, $matches)) { 
    $mydate = $matches['year'] . "-" . $matches['month'] . "-" . $matches['day']; 
    $whatever = date('Y-m-d', strtotime($tgl)); 
    // You can echo it... 
    // echo $matches['year']; 
    // echo $matches['month']; 
    // echo $matches['day']; 
} 

希望這能幫到你。 :D

相關問題