php strtotime反向

时间:2011-12-25 13:27:11

标签: php strtotime

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

2 个答案:

答案 0 :(得分:10)

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

/**
 * 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);
    }
}

答案 1 :(得分:1)

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