2015-06-19 94 views
0

我試圖理解爲什麼這個代碼工作:PHP日期比較不工作

<?php 
// $today = date("d/m/Y"); 
$today = date("Y-m-d"); 
$today_dt = new DateTime($today); 

foreach ($records as $record) { 
} 
?> 

<tr> 
    <?php $dueDate = date("Y-m-d", strtotime($record->getField('Due Date'))); ?> 
    <td><?php echo 'today is: ' . $today; ?></td> 
    <td><?php echo 'expiry date is: ' . $dueDate; ?></td> 
    <td> <?php $expire_dt = new DateTime($dueDate); ?> </td> 
    <td><?php echo $expire_dt < $today_dt ? 'expire time less than today time':'expire time greater than today time';?></td> 

,但是當我改變從Y-m-d日期的格式d/m/Y失敗與錯誤:

<?php 
// $today = date("d/m/Y"); 
$today = date("d/m/Y"); 
$today_dt = new DateTime($today); 

foreach ($records as $record) { 

} 
?> 

    <tr> 
<?php $dueDate = date("d/m/Y", strtotime($record->getField('Due Date'))); ?> 
    <td><?php echo 'today is: ' . $today; ?></td> 
    <td><?php echo 'expiry date is: ' . $dueDate; ?></td> 
    <td><?php $expire_dt = new DateTime($dueDate); ?></td> 
    <td><?php echo $expire_dt < $today_dt ? 'expire time less than today time' : 'expire time greater than today time';?></td> 

錯誤是

'PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (19/06/2015) at position 0 (1)'

它引用該生產線是:

$today_dt = new DateTime($today); 

回答

0

您使用應該是 '毫米/日/年',而不是 'DD /月/年' 的日期格式。

+0

謝謝 - 這是有效的。我不明白爲什麼我必須這樣做。你可以解釋嗎? – user982124

+0

您可以在此頁面獲取解釋[date_create](http://php.net/manual/en/function.date-create.php) – perilla

0

使用DateTime類,您不必按照希望顯示的方式格式化輸入日期,您可以使用格式以任意格式顯示它。

// Get todays date 
$today_dt = new DateTime(); 

// Display date in specified format 
echo $today_dt->format('d/m/Y'); 

Check out the PHP man page for more.