2011-12-25 107 views
6

是否有一些函数timetostr在PHP中,将输出today/tomorrow/next sunday/etc.从给定的时间戳?因此,timetostr(strtotime(x))=xphp strtotime反向

+2

date()。见http://php.net/manual/en/function.date.php – 2011-12-25 13:29:07

+0

@Andypandy:我知道'date()'。我的意思是问,有没有一种直接的功能可以做'strtotime'的反转? – prongs 2011-12-25 13:35:46

+0

如果没有日期,我不知道...你能提供更多的上下文吗?像这样($ timestring = date('l',$ timestamp)不起作用? – 2011-12-25 13:39:21

回答

9

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

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

我收到一个错误:意外的'列表'(T_LIST)。我究竟做错了什么? – hozza 2014-09-11 13:54:32

+0

与PHP版本有什么共同点?我通过声明列表'list($ singular,$ plural,$ factor)= $ scale;'在foreach中并用'$ list'替换foreach中的列表来工作。 – hozza 2014-09-11 14:08:26

+0

这是正确的。 PHP 5.5增加了“使用list()解包嵌套数组”(http://php.net/manual/en/control-structures.foreach.php) – 2014-09-11 15:27:16

1

不能有strtotime反转函数,因为这不是双射。当您使用strtotime时,您从中获得UNIX时间戳的源字符串可以采用许多不同的方式进行格式化。所以如果你决定改变功能,你怎么知道使用什么字符串格式?这可能是2010年8月5日或2000年9月10日等。这正是为什么没有反向函数,但正如Andypandy所说的,你必须使用date(),它允许你实际定义你想结束的字符串格式与...一起。我知道这个问题很旧,但我认为它应该得到这个答案,所以其他用户明白为什么PHP中没有这样的功能。

+5

虽然技术上“正确”这并不回答OP的问题,而只是促进了所有知道程序员的负面刻板印象,他知道比有人问这个问题,另一种方法是这样说 - > http://stackoverflow.com/a/3040437/830899 – unsynchronized 2013-12-25 18:59:11

+3

date(“Ymd”,time())可以完成这项工作。 – Qinjie 2014-12-30 05:00:51