【问题标题】:Calculate time() - minutes or hours or weeks or months or years PHP计算 time() - 分钟或小时或几周或几个月或几年 PHP
【发布时间】:2017-10-20 21:07:44
【问题描述】:

我目前有一段获取字符串的代码。

示例:23 分钟前

我的代码,如果是分钟,获取数字(本例中为 23)。

我想从 time() unix 时间戳值中删除分钟(在这种情况下)。

我试过了:

 $timestamplastcheck = strtotime("-".$minutes." minutes", strtotime(time()));

但它返回错误的日期。

谁能告诉我怎么了?另外,如果小时、周、月和年以相同的方式相加?

非常感谢。

【问题讨论】:

    标签: php time unix-timestamp


    【解决方案1】:

    可以将Date与日期方法modify一起使用,例如:

    $ago = '23 minutes ago';
    $date = (new \DateTime())->modify($ago);
    $timestamplastcheck = $date->getTimestamp()
    
    echo $date->format('c');
    

    有了这个你就不需要解析你的字符串来获取数字了,modify 非常强大。 http://php.net/manual/en/datetime.modify.php

    【讨论】:

    • 我怎样才能返回 $date->format('c');在时间戳unix中也是如此? :p
    • $date->getTimestamp()
    【解决方案2】:

    strtotime(time()) 是废话,返回false

    false 然后被另一个strtotime() 调用转换为0,您所有的相对时间格式都将相对于1.1.1970

    正确的方法是完全省略第二个参数,因为time() 无论如何都是它的默认值:

    $timestamplastcheck = strtotime("-".$minutes." minutes");
    

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多