简体   繁体   English

PHP日期比较不起作用

[英]PHP Date Comparison Not Working

I'm trying to understand why this code works: 我试图理解为什么此代码有效:

<?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>

but when I change the format of the date from Ymd to d/m/Y this fails with an error: 但是,当我将日期格式从Ymd更改为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>

The error is 错误是

'PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (19/06/2015) at position 0 (1)' 'PHP致命错误:消息为'DateTime :: __ construct()的未捕获异常'Exception':无法解析位置0(1)处的时间字符串(19/06/2015)'

The line it references is: 它引用的行是:

$today_dt = new DateTime($today);

Using the DateTime class you don't have to format the input date the way you want it to display, you can display it in any format using format. 使用DateTime类,您不必以希望显示的格式来格式化输入日期,可以使用format以任何格式显示它。

// 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. 有关更多信息,请查看PHP手册页。

您使用的日期格式应为“ mm / dd / yyyy”,而不是“ dd / mm / yyyy”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM