View Single Post
Old 09-24-2007, 11:12 PM   #1 (permalink)
CMellor
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default Two Different Ways to Format the Time

Hello,

I will be giving two methods of converting your unix timestamp into readable format. The most common way to display a unix timestamp in a readable format is to the the date() function, like so:

Code:
date("M D, Y", time());
I'm going to give you two different ways,
  1. First Method: Display if time was posted Today or Yesterday
  2. Second Method: Display if the time was posted X Minutes Ago, X Hours Ago, X Years Ago and more...
Okay, First Method:

Code:
function date_pretty($unix_time, $date_format = 'jS M y, H:m a') {
	$time = $unix_time;
	
	if(date($date_format, $time) == date($date_format)) {
		$msg = "Today @ ".date("H:i a", $time)."";
	}
	elseif(date($date_format, $time) == date($date_format, strtotime("yesterday"))) {
		$msg = "Yesterday @ ".date("H:i a", $time)."";
	}
	else {
		$msg = date($date_format, $time);
	}
	
	return($msg);
}
Usage:
Code:
echo date_pretty($row->time);
Usage w/ custom date
Code:
echo date_pretty(time(), "D, M Y");
Now, the second method!

Code:
function timeago($time) {
	// Set the time, minus your set time
	$diff = time() - $time;
	// Years
    if($diff > 31556926) {
        $years = floor($diff / 31556926);
        $times = ($years == 1) ? $years." Year" : $years." Years";
    }
	// Motnsh
    elseif($diff > 18144000) {
        $months = floor($diff / 18144000);
        $times = ($months == 1) ? $months." Month" : $months." Months";
    }
	// Weeks
    elseif($diff > 604800) {
        $weeks = floor($diff / 604800);
        $times = ($weeks == 1) ? $weeks." Week" : $weeks." Weeks";
    }
	// Days
    elseif($diff > 86400) {
        $days = floor($diff / 86400);
        $times = ($days == 1) ? $days." Day" : $days." Days";
    }
	// Hours
    elseif($diff > 3600) {
        $hours = floor($diff / 3600);
        $times = ($hours == 1) ? $hours." Hour" : $hours." Hours";
    }
	// Minutes
    else {
        $min = ceil($diff / 60);
        $times = ($min == 1) ? $min." Minute" : $min." Minutes";
    }
	// Return output
    return $times;
}
Usage:

Code:
echo timeago($row->time);
I hope somebody can find some use for these code snippets. This is the first time really I've contributed any code, but only because I've had nowhere to do so, and this place seems like the sort of place that it could get some use from the users.

Enjoy!
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote