Reputation: 219
I've got a webpage which records in UNIX when it was last viewed into a datbase field. I want to pull off a report incuding how many days ago this page was last viewed. I'm doing this in PHP
How do i work this out to display? At the moment I have the field showing when it was last accessed by using gmdate("M D Y ", $UNIXTIMESTAMPFIELD) but instead of the date of last access I want to display something like
23 days ago
Thanks
Kieran
Upvotes: 1
Views: 888
Reputation: 19662
That's pretty easy if you're on PHP5.3 or later. Use the DateInterval
object, which can understand unix timestamps and easily output a difference.
What you can do is very, very straightforward. Assume your timestamps are $TS1, $TS2.
Step 1: create the DateTime
objects for each:
$DT1 = new DateTime("@{$TS1}");
$DT2 = new DateTime("@{$TS2}");
Step 2: diff them
$diff = $DT1->diff($DT2);
Step 3: print stuff!
echo "Days: ".$diff->d;
This automatically takes into account timezone settings, amongst other things. It also allows you to easily substract from datetime objects should you need to.
Upvotes: 3
Reputation: 20997
Difference is clearly $diff = time() - $UNIXTIMESTAMPFIELD
(now-event). Not you just have to format it correctly:
function time_diff_to_human($seconds){
// For seconds
if( $seconds < 60){
if( $seconds == 1){
return "a second ago"
}
return sprintf( "%d seconds ago", $seconds);
}
// Minutes
$minutes = round( $seconds/60);
if( $minutes < 60){
if( $minutes == 1){
return "a minute ago"
}
return sprintf( "%d minutes ago", $minutes);
}
// Hours
$hours = round( $minutes/60);
if( $hours < 24){
if( $hours == 1){
return "last hour"
}
return sprintf( "%d hours", $hours);
}
// Add some formatting to days
$days = $months/24;
if( $days < 31){
if( $days == 1){
return 'yesterday';
}
return sprintf( "%d days", $days);
}
// Approx months
$months = round( $days/30);
if( $months < 12){
if( $months == 1){
return "last month"
}
return sprintf( "%d months", $months);
}
// And finally years, note that they are calculated from days
$years = round( $days/365.4);
if( $years == 1){
return "last year"
}
return sprintf( "%d years", $years);
}
Upvotes: 0