【问题标题】:Convert date into timestamp where strtotime has already been used将日期转换为已使用 strtotime 的时间戳
【发布时间】:2014-04-23 23:30:38
【问题描述】:

我正在尝试将接下来 7 天的日期转换为时间戳,以便与数据库中的日期时间戳进行比较以获得一些结果。

此函数用于获取从今天开始的接下来的 7 天

$next_date = date("d/m/Y", strtotime("7 day"))

输出

30/04/2014

现在我再次在 $next_date 变量上运行 strtotime(),该变量保存接下来的 7 天并转换为时间戳。

echo strtotime($next_date);

这不起作用。我关注了这个stackoverflow 答案和其他几个。

【问题讨论】:

    标签: php date


    【解决方案1】:

    作为替代建议,您可以查看 PHP 的内部 DateTime()DateInterval() 类。它使格式之间的转换以及日期/时间的加法和减法更容易一些。 DateInterval 至少需要 PHP 5.3 版。

    一个例子:

    // create a current DateTime
    $currDate = new DateTime();
    
    // copy the current DateTime and
    // add an interval of 7 days
    $nextDate = clone $currDate;
    $nextDate->add(new DateInterval('P7D'));
    
    // both objects are easily converted to timestamps
    echo $currDate->getTimestamp(); // e.g: 1398296728
    echo $nextDate->getTimestamp(); // e.g: 1398901528
    
    // and both can be easily formatted in other formats
    echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
    echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
    

    编辑

    为了完整起见,下面是另一个示例,说明如何将 7 天添加到 DateTime 对象:

    $now  = new DateTimeImmutable();
    $then = $now->modify('+7 days');
    
    var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
    

    产量:

    string(10) "2016-05-24"
    string(10) "2016-05-31"
    

    您也可以使用 DateTime - 此用例的不同之处在于 DateTime::modify() 将修改实例 $now 其中 DateTimeImmutable::modify() 将返回一个新的 DateTimeImmutable 对象 - 所以如果您需要创建一个新的对象同时保留旧对象,这可能是最简洁的方法。

    希望这会有所帮助:)

    【讨论】:

      【解决方案2】:

      先存储strtotime的值?

      $timestamp_in_7_days = strtotime('7 day');
      $next_date = date('d/m/Y', $timestamp_in_7_days);
      

      没有必要在unix时间戳和日期格式之间来回扔时间。

      【讨论】:

      • 确实如此。我只是想补充一下,海报说“它不起作用”。我猜问题是您将 $next_date 格式化为 d/m/Y,并根据 PHP 手册:Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
      • @Kai - 是的,这是正确的。他可以通过拆分字符串,使用 mktime 或其他东西来使其工作,但这是我所看到的最干净的方法;)
      • 是的,如果你没有打败我,我自己也会这么说。 =)
      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多