Skip to content

Instantly share code, notes, and snippets.

@blocksector
Last active December 21, 2015 02:59
Show Gist options
  • Save blocksector/6238788 to your computer and use it in GitHub Desktop.
Save blocksector/6238788 to your computer and use it in GitHub Desktop.
my snippet to override the default toDateString method of Date object. it should returna date string depending on the format the user passed on.it should follow the date formatting of Django.feature:- customizable date formatsample:var date = new Date();document.write( date.toDateString("l F j Y") );todo:- formatting of date according to user in…
// extend date object and define the format method
Date.prototype.toRelativeTime = function () {
// days of week long string
var day_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Month long string
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// the dates
var from_date = this,
current_date = new Date();
// Compute for difference
var time_diff = current_date.getTime() - from_date.getTime();
// convert to sec, min, hr, or day
var sec = Math.floor(time_diff/1000),
min = Math.floor(sec/60),
hr = Math.floor(min/60),
day = Math.floor(hr/24);
// check which string to use
switch( (day>=1)?"day":(hr>=1)?"hr":(min>=1)?"min":(sec>=0)?"sec":null ) {
case "day":
return (day<=7)?day+" day"+((day>=2)?"s":"") + " ago":this.toDateString();
case "hr":
return hr + " hour" + ((hr>=2)?"s":"") + " ago";
case "min":
return min + " minute" + ((min>=2)?"s":"") + " ago";
case "sec":
return (sec>=6)?sec+" seconds ago":"just now";
default:
return "Date is out of range";
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment