2012-09-26 30 views
-1

我注意到Facebook,Twitter以及很多其他网站都在使用相对日期和时间字符串来描述用户的帖子和评论。用php在用户中显示日期格式

例如,“3个月前写的评论”,而不是“2012年9月20日发表的评论”。我决定在我的网站上做同样的事情。在我的网站,我需要显示1天前,2天前,3天前,...... 1周前,2周前,.... 1个月前,2个月前,..... 。1年前,2年前...等

我已经有用户注册日期,需要检查它与当前日期和时间,并需要在我的主页上显示以上样式。

在我的数据库,用户登记的日期格式是这样的..“2012年9月23日9时11分02秒”

任何人可以帮助我建立在PHP这个脚本...,它会极大地appriciated。

谢谢。

+0

哦,不!这么多标点符号。 – hjpotter92

+0

你应该先尝试一下自己,相信我并不艰难 – Tarun

+2

如果你先自己试穿一下,你会在StackOverflow上做得更好。然后,如果遇到麻烦,请回到这里,具体问题:) 我会给你一个提示:阅读date()和strtotime()函数。 –

回答

1

尝试下面的代码,

function time_elapsed_since ($postedDateTime){ 

    $time = time() - $postedDateTime; // to get the time since that moment 

     $tokens = array (
         31536000 => 'year', 
         2592000 => 'month', 
         604800 => 'week', 
         86400 => 'day', 
         3600 => 'hour', 
         60 => 'minute', 
         1 => 'second' 
       ); 

        foreach ($tokens as $unit => $text) { 
         if ($time < $unit) continue; 
         $numberOfUnits = floor($time/$unit); 
         return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':''); 
        } 

    } 

用法:

time_elapsed_since($postedDateTime).' ago'; // 2012-09-23 09:11:02 format 
+0

我dnt喜欢支持勺子喂养的人 – Tarun

+0

它的工作数周和数月。但不能在数秒,数分钟和数小时内工作。假设我刚刚添加了一个配置文件,它不显示1秒前,2秒前...等等,1分钟前,2分钟前..等 – thara

+0

@thara它的工作时间和秒钟。 –

1

与此

function time_ago($time) { 

    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade"); 
    $lengths = array("60","60","24","7","4.35","12","10"); 

    $now = time(); 

    $difference = $now - $time; 
    $tense = "ago"; 

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
     $difference /= $lengths[$j]; 
    } 

    $difference = round($difference); 

    if($difference != 1) { 
     $periods[$j].= "s"; 
    } 

    return "$difference $periods[$j] 'ago' "; 
} 
+0

请正确缩进您的代码。 – hakre

+0

它的工作数周和数月。但不能在数秒,数分钟和数小时内工作。假设我刚刚添加了一个配置文件,它不显示1秒前,2秒前...等等和1分钟前,2分钟前..等 – thara

+0

@thara:你可以做自己的任何东西吗? – Parth

0

即时猜测他们正在使用unixtime即自1970年以来的秒数尝试(其是标准的)。我建议,也应该保持你的日期格式。如果他们使用的UNIX时间,你可以使用下面的日期功能在PHP将其转换为您的格式上面:

<?php 
date('Y-m-t H:i:s', $facebookTime); 

问候, 凯文