可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to somehow take a unix timestamp and output it like below
Can this be done with MySQL? Or php
Mike 7s ago Jim 44s ago John 59s ago Amanda 1m ago Ryan 1m ago Sarah 1m ago Tom 2m ago Pamela 2m ago Ruben 3m ago Pamela 5h ago
As you can guess i only wanna print the minute, not minutes and seconds(1m 3s ago)
What should I look into?
回答1:
Yes it can be done. See related post
$before // this is a UNIX timestamp from some time in the past, maybe loaded from mysql $now = time() $diff = $now - $before; if( 1 > $diff ){ exit('Target Event Already Passed (or is passing this very instant)'); } else { $w = $diff / 86400 / 7; $d = $diff / 86400 % 7; $h = $diff / 3600 % 24; $m = $diff / 60 % 60; $s = $diff % 60; return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!" }
回答2:
PHP 5.3 and newer have DateTime
objects that you can construct with data coming back from a database. These DateTime
objects have a diff
method to get the difference between two dates as a DateInterval
object, which you can then format
.
Edit: corrected sub
to diff
.
Edit 2: Two catches with doing it this way:
DateTime
's constructor doesn't appear to take a UNIX timestamp... unless prefixed with an @, like this: $startDate = new DateTime('@' . $timestamp);
- You won't know what the largest unit is without manually checking them. To get an individual field, you still need to use format, but with just a single code... Something like
$years = $dateDiff->format('y');
回答3:
function sECONDS_TO_DHMS($seconds) { $days = floor($seconds/86400); $hrs = floor($seconds / 3600); $mins = intval(($seconds / 60) % 60); $sec = intval($seconds % 60); if($days>0){ //echo $days;exit; $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT); $hours = $hrs-($days*24); $return_days = $days." Days "; $hrs = str_pad($hours,2,'0',STR_PAD_LEFT); }else{ $return_days=""; $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT); } $mins = str_pad($mins,2,'0',STR_PAD_LEFT); $sec = str_pad($sec,2,'0',STR_PAD_LEFT); return $return_days.$hrs.":".$mins.":".$sec; } echo sECONDS_TO_DHMS(2); // Output 00:00:02 echo sECONDS_TO_DHMS(96000); // Output 1 Days 02:40:00
回答4:
PHP's date() function
as well as time() and some others that are linked in those docs
This can also be done in Mysql with date and time functions
回答5:
You can try my Timeago
suggestion here.
It can give outputs like this:
You opened this page less than a minute ago. (This will update every minute. Wait for it.)
This page was last modified 11 days ago.
Ryan was born 31 years ago.
回答6:
I dont have a mysql server at hand, but a combination of the following commands should get you something like what you want.
DATEDIFF
AND
DATEFORMAT