Home » Software Development » Time Ago for Dates using SugarJS

Time Ago for Dates using SugarJS

Here’s how to get nice clean dates in your GUI. This shows relative dates for the current day, i.e. “2 hours ago”, and “month day” for dates in this year, for anything older that this year, i.e. all posts from last year and beyond it simply adds the year as “month day year”.

I’m using Handlebars with MeteorJS, but the Javascript code below is still… Javascript, with SugarJS, so you should be able to figure it out with a cut & paste job if your using something other than Meteor / Handlebars.

Make sure you add: www.sugarjs.com to your project, otherwise you’ll be a fish out of water.

Here’s the Handlebars helper, just pass in a date created with JavaScripts Date().  i.e.

In the Handlebars template:

  {{fn_timeAgo createDate}}   

createDate is a DB field created using:

  createDate: new Date()  

And finally… the main code — you can customize this to your liking, it’s pretty simple to change formatting, check the SugarJS page for more ideas:

Handlebars.registerHelper('fn_timeAgo', function(IN_date) {

  var ret_val;
  var new_date = Date.create(IN_date); // uses SugarJS create().

  // All methods on new_date are from SugarJS.
  if ( new_date.is('today') ) {  
    ret_val = new_date.relative();  
  }
  else if ( new_date.is('this year') ) {   
    ret_val = new_date.format('{Mon} {dd}'); 
  }
  else if ( new_date.isBefore('this year') ) { 
    ret_val = new_date.format('{Mon} {dd} {yyyy}');
  }
  else {
    console.log("ERROR: in Handlebars helper: fn_timeAgo().")
  }

  return ret_val;

});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: