Created
July 22, 2012 15:42
-
-
Save anuith/3160019 to your computer and use it in GitHub Desktop.
Javascript Pretty Date formatter
This file contains 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
/* | |
Pretty Date script modified from John Resig here http://ejohn.org/blog/javascript-pretty-date | |
*/ | |
function relativeDateTime (tdate) { | |
var system_date; | |
if (typeof (tdate) === "number") { | |
tdate = new Date(tdate).toString(); | |
} | |
if (navigator.userAgent.match(/MSIE\s([^;]*)/)) { | |
system_date = Date.parse(tdate.replace(/( \+)/, ' UTC$1')) | |
} else { | |
system_date = new Date(Date.parse(tdate)); | |
} | |
var user_date = new Date(); | |
var diff = Math.floor((user_date - system_date) / 1000); | |
if (diff <= 1) { return "just now"; } | |
if (diff < 20) { return diff + " seconds ago"; } | |
if (diff < 40) { return "half a minute ago"; } | |
if (diff < 60) { return "less than a minute ago"; } | |
if (diff <= 90) { return "one minute ago"; } | |
if (diff <= 3540) { return Math.round(diff / 60) + " minutes ago"; } | |
if (diff <= 5400) { return "1 hour ago"; } | |
if (diff <= 86400) { return Math.round(diff / 3600) + " hours ago"; } | |
if (diff <= 129600) { return "1 day ago"; } | |
if (diff < 604800) { return Math.round(diff / 86400) + " days ago"; } | |
if (diff <= 777600) { return "1 week ago"; } | |
// Clock and calendar identifiers | |
var calendarIdentifiers = Windows.Globalization.CalendarIdentifiers; | |
var clockIdentifiers = Windows.Globalization.ClockIdentifiers; | |
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate", | |
["en-US"], "US", calendarIdentifiers.gregorian, clockIdentifiers.twentyFourHour); | |
return "on " + formatter.format(new Date(tdate)); | |
} | |
function parseDate (timeString) { | |
var date = Date.parse((timeString || "").replace(/-/g, "/").replace(/TZ/g, " ").replace(/( \+)/, ' UTC$1')); | |
return date; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment