outaTiME

Do you have a pretty date?

Posted in development, javascript by outaTiME on January 30, 2008

John Resig has created a little script to give you pretty dates that Web 2.0 know and love (thanks Rails):

JAVASCRIPT:

  1.  
  2. prettyDate(“2008-01-28T20:24:17Z”) // => "2 hours ago"
  3. prettyDate(“2008-01-27T22:24:17Z”) // => "Yesterday"
  4. prettyDate(“2008-01-26T22:24:17Z”) // => "2 days ago"
  5. prettyDate(“2008-01-14T22:24:17Z”) // => "2 weeks ago"
  6.  

The library is short and sweet:

JAVASCRIPT:

  1.  
  2. /*
  3. * JavaScript Pretty Date
  4. * Copyright (c) 2008 John Resig (jquery.com)
  5. * Licensed under the MIT license.
  6. */
  7.  
  8. // Takes an ISO time and returns a string representing how
  9. // long ago the date represents.
  10. function prettyDate(time){
  11.         var date = new Date((time || “”).replace(/-/g,“/”).replace(/[TZ]/g,” “)),
  12.                 diff = (((new Date()).getTime() – date.getTime()) / 1000),
  13.                 day_diff = Math.floor(diff / 86400);
  14.                        
  15.         if ( isNaN(day_diff) || day_diff <0 || day_diff>= 31 )
  16.                 return;
  17.                        
  18.         return day_diff == 0 && (
  19.                         diff <60 && “just now” ||
  20.                         diff <120 && “1 minute ago” ||
  21.                         diff <3600 && Math.floor( diff / 60 ) + ” minutes ago” ||
  22.                         diff <7200 && “1 hour ago” ||
  23.                         diff <86400 && Math.floor( diff / 3600 ) + ” hours ago”) ||
  24.                 day_diff == 1 && “Yesterday” ||
  25.                 day_diff <7 && day_diff + ” days ago” ||
  26.                 day_diff <31 && Math.ceil( day_diff / 7 ) + ” weeks ago”;
  27. }
  28.  

(Via Ajaxian.)

One Response

Subscribe to comments with RSS.

  1. Affodiatimefak said, on August 2, 2008 at 8:49 pm

    Tahnks for posting


Leave a Reply