Skip to content

Instantly share code, notes, and snippets.

@remy
Created September 2, 2012 23:10
Show Gist options
  • Save remy/3605484 to your computer and use it in GitHub Desktop.
Save remy/3605484 to your computer and use it in GitHub Desktop.
Super simple library for date time formatting.
var dateUtil = function () {
var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return {
time: function (date) {
var hour = date.getHours(),
min = date.getMinutes() + "",
ampm = 'AM';
if (hour == 0) {
hour = 12;
} else if (hour == 12) {
ampm = 'PM';
} else if (hour > 12) {
hour -= 12;
ampm = 'PM';
}
if (min.length == 1) {
min = '0' + min;
}
return hour + ':' + min + ' ' + ampm;
},
date: function (date) {
var mon = monthDict[date.getMonth()],
day = date.getDate()+'',
dayi = ~~(day),
year = date.getFullYear(),
thisyear = (new Date()).getFullYear(),
th = 'th';
// anti-'th' - but don't do the 11th, 12th or 13th
if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
th = 'st';
} else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
th = 'nd';
} else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
th = 'rd';
}
if (day.substr(0, 1) == '0') {
day = day.substr(1);
}
return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
},
shortdate: function (date) {
var mon = monthDict[date.getMonth()],
day = date.getDate()+'',
year = date.getFullYear(),
thisyear = (new Date()).getFullYear();
if (thisyear === year) {
return day + ' ' + mon;
} else {
return day + ' ' + mon + (year+'').substr(2, 2);
}
},
datetime: function (date) {
return this.time(date) + ' ' + this.date(date);
},
relative: function (date) {
var relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
delta = ~~((relative_to.getTime() - date.getTime()) / 1000),
r = '';
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta <= 1) {
r = '1 second ago';
} else if (delta < 60) {
r = delta + ' seconds ago';
} else if (delta < 120) {
r = '1 minute ago';
} else if (delta < (45*60)) {
r = (~~(delta / 60)) + ' minutes ago';
} else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
r = '1 hour ago';
} else if (delta < (24*60*60)) {
r = (~~(delta / 3600)) + ' hours ago';
} else {
r = this.shortdate(date);
}
return r;
}
};
}();
@jtokoph
Copy link

jtokoph commented Sep 5, 2012

} else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
        r = '1 hour ago';
}

179 minutes = 1 hour?
sdf

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