【问题标题】:php strtotime reversephp strtotime反向
【发布时间】:2012-01-27 14:58:47
【问题描述】:

php 中是否有一些函数timetostr 会从给定的时间戳输出today/tomorrow/next sunday/etc.?这样timetostr(strtotime(x))=x

【问题讨论】:

  • @Andypandy:我知道date()。我的意思是问,是否有一个直接函数可以反转strtotime
  • 如果不是日期,我不知道...您能提供更多上下文吗?像这样 ($timestring = date('l', $timestamp) 不起作用?
  • 我写了一个。刚刚在($timestamp-strtodate('today'))/86400 上添加了一个开关盒。我只是想知道php中是否已经有一个内置函数。

标签: php strtotime


【解决方案1】:

这可能对来这里的人有用。

/**
 * Format a timestamp to display its age (5 days ago, in 3 days, etc.).
 *
 * @param   int     $timestamp
 * @param   int     $now
 * @return  string
 */
function timetostr($timestamp, $now = null) {
    $age = ($now ?: time()) - $timestamp;
    $future = ($age < 0);
    $age = abs($age);

    $age = (int)($age / 60);        // minutes ago
    if ($age == 0) return $future ? "momentarily" : "just now";

    $scales = [
        ["minute", "minutes", 60],
        ["hour", "hours", 24],
        ["day", "days", 7],
        ["week", "weeks", 4.348214286],     // average with leap year every 4 years
        ["month", "months", 12],
        ["year", "years", 10],
        ["decade", "decades", 10],
        ["century", "centuries", 1000],
        ["millenium", "millenia", PHP_INT_MAX]
    ];

    foreach ($scales as list($singular, $plural, $factor)) {
        if ($age == 0)
            return $future
                ? "in less than 1 $singular"
                : "less than 1 $singular ago";
        if ($age == 1)
            return $future
                ? "in 1 $singular"
                : "1 $singular ago";
        if ($age < $factor)
            return $future
                ? "in $age $plural"
                : "$age $plural ago";
        $age = (int)($age / $factor);
    }
}

【讨论】:

  • 我收到一个错误:意外的“列表”(T_LIST)。我做错了什么?
  • 与 PHP 版本有关吗?我通过在 foreach 中声明列表 list($singular, $plural, $factor) = $scale; 并将 foreach 婴儿车中的列表替换为 $list 来实现它
  • 没错。 PHP 5.5 添加了“使用 list() 解包嵌套数组”(php.net/manual/en/control-structures.foreach.php)
  • 谢谢!这为我节省了很多时间。这应该是一个内置函数!
【解决方案2】:

不可能有strtotime 反向函数,因为这不是双射。当您使用strtotime 时,您从中获取UNIX 时间戳的源字符串可以采用多种不同的方式进行格式化。所以如果你决定反转函数,你怎么知道要使用什么字符串格式呢?很可能是 2010-08-05 或 2000 年 9 月 10 日等。这正是没有反向功能的原因,但正如 Andypandy 正确所说,您必须使用date(),它允许您实际定义您希望的字符串格式结束。我知道这个问题很老,但我认为它应该得到这个答案,以便其他用户理解为什么 PHP 中没有这样的函数。

【讨论】:

  • 虽然在技术上是“正确的”,但这并不能回答 OP 的问题,而只是加深了对比提出问题的人更了解的无所不知的程序员的负面刻板印象。另一种方法是这样说--> stackoverflow.com/a/3040437/830899
  • date("Y-m-d",time()) 可以胜任。
猜你喜欢
  • 2012-12-02
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多