MySQL和PHP计算注册日期的分钟和小时数?

时间:2010-05-20 03:09:21

标签: php mysql

如何计算自从注册日期注册的成员使用PHP&存储在我的MySQL数据库中作为日期时间的分钟和小时数。的MySQL。

这是我到目前为止所拥有的。

date('F j, Y g:i:s A', strtotime($row['rdate']))

3 个答案:

答案 0 :(得分:2)

最干净的答案是要求数据库SQL解析器执行此操作。

SELECT
   DATEDIFF(NOW(), registered_date) AS days_since_registration,
   TIMEDIFF(NOW(), registered_date) AS hours_since_registration
FROM users;

假设列registered_date的格式为DATETIME

顺便说一句,在查询中使用UNIX_TIMESTAMP()而不是使用strftime()也更好,因为MySQL具有日期时间的内部格式,并且可以将其转换为unix时间而无需猜测。 strftime()不太可能出现问题,但必须解析日期格式并涉及猜测。

答案 1 :(得分:0)

看起来你几乎拥有它,这给出了基本原则:

$seconds = time() - strtotime( $row['rdate'] );
$minutes = $seconds / 60;
$hours = $seconds / 3600;
$days = $seconds / 86400;
$weeks = $seconds / 604800;

答案 2 :(得分:0)

时间以前从这里的例子中得到的话 http://php.net/manual/en/function.time.php

就是你想要的东西

示例输出1小时3分钟前

public static function timeAgo($date){
            if(empty($date)) {
                return "No date provided";
            }

            if( Settings::read( 'localize') ){
                $periods = array("{{second}}", "{{minute}}", "{{hour}}", "{{day}}", "{{week}}", "{{month}}", "{{year}}", "{{decade}}");
            }else{
                $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
            }
            $lengths = array("60","60","24","7","4.35","12","10");

            $now = time();

            strtotime($date);   

            //

            // check validity of date
            if(empty($unix_date)) {   
                return "Bad date";
            }

            // is it future date or past date
            if($now > $unix_date) {   
                $difference     = $now - $unix_date;
                $tense         = "ago";

            } else {
                $difference     = $unix_date - $now;
                $tense         = "from now";
            }

            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] {$tense}";
        }