Created
January 7, 2017 23:18
-
-
Save trg1984/f62bccfad959d8f525027d87ae40c9a8 to your computer and use it in GitHub Desktop.
Converts a Date object to its relative verbal description.
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
var timeIntervals = [ | |
{start: 0, caption: 'Just now.'}, | |
{start: 60 * 1000, caption: 'A minute ago.'}, | |
{start: 2 * 60 * 1000, caption: '@1 minutes ago.'}, | |
{start: 60 * 60 * 1000, caption: 'An hour ago.'}, | |
{start: 2 * 60 * 60 * 1000, caption: '@2 hours ago.'}, | |
{start: 24 * 60 * 60 * 1000, caption: 'Yesterday.'}, | |
{start: 2 * 24 * 60 * 60 * 1000, caption: '@3 days ago.'}, | |
{start: 7 * 24 * 60 * 60 * 1000, caption: 'A week ago.'}, | |
{start: 14 * 24 * 60 * 60 * 1000, caption: '@4 weeks ago.'}, | |
{start: 30 * 24 * 60 * 60 * 1000, caption: 'A month ago.'}, | |
{start: 60 * 24 * 60 * 60 * 1000, caption: '@5 months ago.'}, | |
{start: 365 * 24 * 60 * 60 * 1000, caption: 'A year ago.'}, | |
{start: 2 * 365 * 24 * 60 * 60 * 1000, caption: '@6 years ago.'}, | |
{start: 5 * 365 * 24 * 60 * 60 * 1000, caption: 'A long time ago.'} | |
]; | |
function __sortTimeIntervals(a, b) { | |
return a.start == b.start ? 0 : a.start < b.start ? -1 : 1; | |
} | |
sort(timeIntervals, __sortTimeIntervals); | |
function announceTime(t) { | |
if (!(t instanceof Date)) return ''; | |
var now = new Date(); | |
var diff = now - t; | |
// Find the right index | |
var i = 0; | |
while (i < timeIntervals.length - 1 && diff < timeIntervals[i + 1].start) ++i; | |
replaces = [ | |
diff / (60 * 1000) | 0, | |
diff / (60 * 60 * 1000) | 0, | |
diff / (24 * 60 * 60 * 1000) | 0, | |
diff / (7 * 24 * 60 * 60 * 1000) | 0, | |
diff / (30 * 24 * 60 * 60 * 1000) | 0, | |
diff / (365 * 24 * 60 * 60 * 1000) | 0 | |
]; | |
var result = timeIntervals[i].caption; | |
for (var i = 0; i < replaces.length; ++i) result.replace('@' + i, replaces[i]); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment