Skip to content

Instantly share code, notes, and snippets.

@jimdoescode
Last active December 22, 2015 08:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimdoescode/6444608 to your computer and use it in GitHub Desktop.
Save jimdoescode/6444608 to your computer and use it in GitHub Desktop.
Easily format a past date with this object. It has two public methods one that will give a rough estimate with the largest part of time. Something like: 2 hours ago. The second will give you all the parts of time that have elapsed as an object. Parts that are too large are returned as null. Check the comments for more information.
/*
License: MIT
Easily formattable date difference.
DateFromNow(someDate).simple(); //ex. returns '3 days ago';
DateFromNow(someDate).parts(); //ex. returns {years: null, months: null, days: 3, hours: 8, minutes: 52, seconds: 43};
*/
function DateFromNow(date)
{
var milliseconds = {year: 3.15569e+10, month: 2.62974e+9, day: 86400000, hour: 3600000, minute: 60000, second: 1000};
var difference = Date.now() - Date.parse(date);
var timeConvert = function(type)
{
var time = difference > milliseconds[type] ? Math.floor(difference / milliseconds[type]) : null;
difference = difference % milliseconds[type];
return time;
};
//Returns a string of the largest part of
//time for the time differece.
var simple = function()
{
for(var key in milliseconds)
{
var converted = timeConvert(key);
if(converted !== null)
{
key += converted > 1 ? 's' : '';
return [converted, key, 'ago'].join(' ');
}
}
return 'just now';
};
//Return all the parts of the time difference
var parts = function()
{
return {
years: timeConvert('year'),
months: timeConvert('month'),
days: timeConvert('day'),
hours: timeConvert('hour'),
minutes: timeConvert('minute'),
seconds: timeConvert('second')
};
};
return {simple: simple, parts: parts};
}
@jimdoescode
Copy link
Author

http://codemana.com/6444608#DateFromNow.js-L10 Testing comments that appear on specific lines of the application

@jimdoescode
Copy link
Author

http://codemana.com/6444608#DateFromNow.js-L13 Commenting just to comment...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment