2014-11-16 68 views
-1

您好,我有日期格式d/m/Y,我想將其更改爲Y-m-d。 我用這個代碼:將日期格式從d/m/Y更改爲Y-m-d

$check_in = '31/12/2014'; 
$check_out = '2/01/2015'; 

$md = explode("/", $check_in); // split the array 
$nd = $md[2]."-".$md[1]."-".$md[0]; // join them together 
$check_in_new = date('Y-m-d', strtotime($nd)); 

$mmd = explode("/", $check_out); // split the array 
$nnd = $md[2]."-".$mmd[1]."-".$mmd[0]; // join them together 
$check_out_new = date('Y-m-d', strtotime($nnd)); 

其做工精細,但如果我嘗試爲02/01/2015年(2015年),轉換的結果是 -01-02 其轉換年到

任何幫助???

+1

在倒數第二行中將'$ md [2]'更改爲'$ mmd [2]'...並讀取DateTime對象。 – DCoder

+0

只是一個變量不匹配。 :( – Riad

+0

非常感謝你這是問題:) 我非常感謝你,你幫了我很多。 – pey22

回答

2

我建議利用在這種情況下DateTime類,並提供適當的格式,它與createFromFormat,而不是膨脹的字符串:

$check_in = '31/12/2014'; 
$check_out = '2/01/2015'; 

$check_in_new = DateTime::createFromFormat('d/m/Y', $check_in); 
$check_out_new = DateTime::createFromFormat('d/m/Y', $check_out); 

echo $check_in_new->format('Y-m-d') . '<br/>'; 
echo $check_out_new->format('Y-m-d') . '<br/>'; 

編號:http://php.net/manual/en/class.datetime.php

0

如果你想繼續你的方式現在正在做,你可以很容易地通過以下方式:

$check_in = '31/12/2014'; 
$check_out = '2/01/2015'; 
$check_in_new = implode('-',array_reverse(explode('/',$check_in))); 
$check_out_new = implode('-',array_reverse(explode('/',$check_out))); 

但是有一個更好的方法來做到這一點:

//Set format 
$format = 'Y-m-d'; 
$dto = new DateTime(strtotime($check_in)); 
$check_in_new = $dto->format($format);