【问题标题】:Date difference in timestamp and normal dates in MYSQLMYSQL中时间戳和正常日期的日期差异
【发布时间】:2013-01-28 13:50:48
【问题描述】:

我有一个包含 2 个日期列的表,一个是时间戳值(例如 1359380165),另一个是正常日期时间值(例如 2013-01-28 08:32:53)。

我想找出现在(当前)和上面列出的这些日期之间的时间间隔。所以结果将是例如。

  1. Daniel 5 分钟前更改了密码
  2. Jeniffer 3 天前删除了她的电话号码。

有什么想法吗?

【问题讨论】:

    标签: php mysql datetime


    【解决方案1】:

    这个函数应该做一些类似于你所追求的事情,试一试,它只需要像你的'1359380165'一样传递给它的unix时间戳。

    function getRelativeTime($timestamp)
    {
        $timeDifference = time() - $timestamp;
        $timePeriods    = array('second', 'minute', 'hour', 'day', 'week','month', 'years', 'decade');
        $timeLengths    = array('60', '60', '24', '7', '4.35', '12', '10');
    
        if ($timeDifference > 0)
        {
                $timeSuffix = 'ago';
        }
        else
        {
            $timeDifference = -$timeDifference;
            $timeSuffix     = 'to go';
        }
    
        for($i = 0; $timeDifference >= $timeLengths[$i]; $i++)
        {
            $timeDifference/= $timeLengths[$i];
            $timeDifference = round($timeDifference);
        }
    
        if($timeDifference != 1) $timePeriods[$i].= 's';
    
        return $timeDifference . ' ' . $timePeriods[$i] . ' ' . $timeSuffix;
    }
    

    【讨论】:

      【解决方案2】:

      假设这样的表:

      我的表

      id int unsigned not null auto_increment primary key
      username varchar(45) not null
      utime int
      dtime timestamp
      

      为什么不直接构造查询以便 PHP 以相同格式接收两个时间戳?像这样的:

      SELECT id, username, FROM_UNIXTIME(utime, '%Y-%m-%d %H.%i.%s') AS ut, dtime AS dt FROM mytable;
      

      SELECT id, username, utime AS ut, UNIX_TIMESTAMP(dtime) as dt FROM mytable;
      

      那么你就可以用同样的方式处理 ut 和 dt 了。

      有一个很好的相对时间函数here。它需要一个 unix 时间戳。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-16
        • 2021-01-23
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        相关资源
        最近更新 更多