2012-03-19 52 views
1

我有几年前写过的以下函数。它从我的数据库中获取日期时间并以更好的格式显示它。需要重写日期显示功能

function formatTime($dateTime){ 
// show time only if posted today 
if (date('Ymd') == date('Ymd', strtotime($dateTime))) { 
    $dt = date('g:i a', strtotime($dateTime)); 
} else { 
    // if not the same year show YEAR 
    if (date('Y') == date('Y', strtotime($dateTime))) { 
     $dt = date('M j', strtotime($dateTime)); 
    } else { 
     $dt = date('M j, Y', strtotime($dateTime)); 
    } 
} 

return $dt; 
} 

我使用服务器时间,这是我的CST。昨天我有一位来自澳大利亚的用户指出,对他来说,自从他进入完全不同的时区之后,实际上是一天之前(与某些时候的输出相比:)。

我决定重写我的功能,这样说:小时

  • 如果不到一分钟时间>秒前
  • 如果在一个小时>#分钟前
  • 1-2之间>的上小时前
  • 2 - 24小时>天前
  • 2 - 7日>#天前
  • - 7天一个月>#星期前
  • 1 - 2个月>过了一个月
  • 后,我可以只显示一个日期

是否有你也许意识到这样做的任何功能,如果不是我怎么会修改这个吗?

谢谢。

回答

2
function formatTime ($dateTime) { 

    // A Unix timestamp will definitely be required 
    $dateTimeInt = strtotime($dateTime); 

    // First we need to get the number of seconds ago this was 
    $secondsAgo = time() - $dateTimeInt; 

    // Now we decide what to do with it 
    switch (TRUE) { 

    case $secondsAgo < 60: // Less than a minute 
     return "$secondsAgo seconds ago"; 

    case $secondsAgo < 3600: // Less than an hour 
     return floor($secondsAgo/60)." minutes ago"; 

    case $secondsAgo < 7200: // Less than 2 hours 
     return "over an hour ago"; 

    case $secondsAgo < 86400: // Less than 1 day 
     return "1 day ago"; // This makes no sense, but it is what you have asked for... 

    case $secondsAgo < (86400 * 7): // Less than 1 week 
     return floor($secondsAgo/86400)." days ago"; 

    case $secondsAgo < (86400 * 28): // Less than 1 month - for the sake of argument let's call a month 28 days 
     return floor($secondsAgo/(86400 * 7))." weeks ago"; 

    case $secondsAgo < (86400 * 56): // Less than 2 months 
     return "over a month ago"; 

    default: 
     return date('M j, Y', $dateTimeInt); 

    } 

} 

这绝不是完美无瑕的,尤其是你的要求没有意义(见注释)之一,但希望它应该让你在正确的方向一推,并说明了如何使用switch来允许您轻松地添加和删除行为中的项目/选项。

+0

哦,这太棒了!是的,1天前没有任何意义。我想我可以使用小时,直到24>昨天> 48小时:) – santa 2012-03-19 17:59:05