【问题标题】:Can date() be compared like this? [duplicate]date() 可以这样比较吗? [复制]
【发布时间】:2016-03-30 05:56:39
【问题描述】:

我在比较日期/时间时遇到了一些问题。

我有一个工作代码突然停止工作。现在我对其进行了一些更改,由于某种原因 UNIX 时间不正确。

Utime 和 nexttime 现在只是一个示例字符串,但在代码中 Utime 是最后一次更新,nexttime 是根据 Utime 计算的下一次更新。

例子:

 $Utime = "201603300450"; // YmdHi 2016 03 30 04:50
 $nexttime = "201603300520"; 
 if (date("YmdHi")>=$Utime && date("YmdHi")>=$nexttime)

这是比较时间值的安全方法吗?我对 strtotime 有一些问题,这就是我问的原因。

【问题讨论】:

  • 那你是怎么使用strtotime的?
  • strtotime 有什么问题?
  • If (strtotime(date("YmdHi"))>=strtotime($Utime) && strtotime(date("YmdHi"))>=strtotime($nexttime) ) |||||||问题是 $nexttime 的值比“now”高,即使日期和时间更低。
  • 夏令时有问题?
  • 对不起,我的意思是反过来。下次比现在低

标签: php date


【解决方案1】:

您应该将日期转换为 DateTime 对象:

<?php

$Utime = "201603300450";
$nexttime = "201603300520";

$dateUtime = DateTime::createFromFormat('YmdHi', $Utime);
$datenexttime = DateTime::createFromFormat('YmdHi', $nexttime);

$nowDate = DateTime::createFromFormat('YmdHi', date('YmdHi'));

if ($nowDate>=$dateUtime && $nowDate>=$datenexttime)
    //do your stuff...

【讨论】:

  • 哦哦!你让我半途而废!只是这个没有正确构建$nowDate
  • 看起来不错。会试试的。。
  • 等待它有问题 :) 让我们先解决这个问题,然后您应该尝试一下。如果没有该修复,它将无法正常工作,您将被推迟
【解决方案2】:

Strtotime 应该可以正常工作,但您应该坚持使用有效的格式。 "Y-m-d H:i:s" 是 strtotime 的有效格式。

希望对你有帮助:)

【讨论】:

  • 所以我必须使用那种格式才能工作?
  • 不,你不一定要使用那种格式
【解决方案3】:

strtotime() 是这方面的好帮手。

查看strtotime

$Utime = "201603300450";
$nexttime = "201603300520";
if ( strtotime('now') >= strtotime($Utime) && strtotime('now') >= strtotime($nexttime) )

【讨论】:

  • 这与我在上面在 cmets 中发布的代码完全相同,但不起作用。
  • 这和你还在搞日期函数不一样。我非常简单地使用 now 和有效的日期格式和中提琴!
猜你喜欢
  • 2013-01-25
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2018-10-14
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多