dtid30526 2011-05-14 14:55
浏览 70
已采纳

将日期时间格式从Mysql转换为更友好的格式,如:“3天12小时前”

i have some dates retrived using php from my mysql server in the conventional format: 2011-05-13 12:22:11 , how can i convert this to: 3 days and 12 hours ago. Thanks a lot!

  • 写回答

4条回答 默认 最新

  • drfcaw7460 2011-05-14 15:10
    关注

    For your troubles (source) - the internet is awesome:

    /* takes an argument in unix time (seconds) */
    function time_since($original) {
        // array of time period chunks
        $chunks = array(
            array(60 * 60 * 24 * 365 , 'year'),
            array(60 * 60 * 24 * 30 , 'month'),
            array(60 * 60 * 24 * 7, 'week'),
            array(60 * 60 * 24 , 'day'),
            array(60 * 60 , 'hour'),
            array(60 , 'minute'),
        );
    
        $today = time(); /* Current unix time  */
        $since = $today - $original;
    
        // $j saves performing the count function each time around the loop
        for ($i = 0, $j = count($chunks); $i < $j; $i++) {
    
            $seconds = $chunks[$i][0];
            $name = $chunks[$i][1];
    
            // finding the biggest chunk (if the chunk fits, break)
            if (($count = floor($since / $seconds)) != 0) {
                // DEBUG print "<!-- It's $name -->
    ";
                break;
            }
        }
    
        $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
    
        if ($i + 1 < $j) {
            // now getting the second item
            $seconds2 = $chunks[$i + 1][0];
            $name2 = $chunks[$i + 1][1];
    
            // add second item if it's greater than 0
            if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
                $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
            }
        }
        return $print;
    }
    
    echo time_since(strtotime('2011-05-13 12:22:11')); // 1 day, 2 hours
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程