需要重写日期显示函数


Need to rewrite function for date display

我几年前写了以下函数。它从我的数据库中获取日期时间,并以更好的格式显示它。

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个月>超过一个月
  • 之后我就可以约会了

你可能知道这样做有什么功能吗?如果没有,我将如何修改这个功能?

谢谢。

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来轻松地添加和删除行为中的项目/选项。