SiteCrafting, Inc.

18 Nov

A Matter of Time (and Dates)

When you talk to someone, would you be more likely to say something like "...I came back yesterday about noon," or, "...I came back November 17th, 2010 at 12:23pm"? I'd imagine, unless you're a robot, most people would choose the former over the latter. Shouldn't our web apps do the same?



Social media has opened up a form of online conversation that often takes a casual tone that better matches a real life conversation than something like a business email or paper letter. Likewise, that conversation moves ahead so much faster than before, the element of time relative to where you currently are may make more sense then a precise measurement down to the second.

On sites like Twitter, Facebook, and within some of the apps we build, dates and times are displayed more conversationally using terms like "yesterday", "today", "noon", "this morning", etc. Here's a quick PHP function you could easily expand upon for your needs, but helps clean up dates to make things flow more like most people think and talk.

function friendly_date($date_given) {
$date_given = strtotime($date_given);
$friendly_date = "";

$this_year = date("Y");
$yesterday = mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
$last_week = mktime(0, 0, 0, date("m"), date("d")-7, date("Y"));
$today = date("U");
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("Y"));

// # days ago
if( $date_given < $yesterday && $date_given > $last_week ) {
$today_timestamp = strtotime(date("Y-m-d", $today));
$given_timestamp = strtotime(date("Y-m-d", $date_given));
$friendly_date = ($today_timestamp-$given_timestamp)/86400 . " days ago";
// yesterday
} elseif( date("Y-m-d", $date_given) == date("Y-m-d", $yesterday) ) {
$friendly_date = "yesterday";
// today
} elseif( date("Y-m-d", $date_given) == date("Y-m-d", $today) ) {
$friendly_date = "today";
// tomorrow
} elseif( date("Y-m-d", $date_given) == date("Y-m-d", $tomorrow) ) {
$friendly_date = "tomorrow";
// actual date
} else {
$friendly_date = date("M j", $date_given);

// omit year if current
if( date("Y", $date_given) != $this_year ) {
$friendly_date .= date(", Y", $date_given);
}
}

return $friendly_date;
}
Coding Techniques, Design, Odds 'n Ends, PHP
by Kevin Freitas | 11/18/2010 10:30am | Comments (0)

No comments found.


Leave a Comment




* required    Comment Guidelines