Last active
December 22, 2015 08:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://codemana.com/6444608#DateFromNow.js-L13 Commenting just to comment...