Skip to content

Instantly share code, notes, and snippets.

@ftorre104
Created September 2, 2014 15:57
Show Gist options
  • Save ftorre104/311304f1e928fac0d068 to your computer and use it in GitHub Desktop.
Save ftorre104/311304f1e928fac0d068 to your computer and use it in GitHub Desktop.
User-friendly timestamp formatting
function formatTimeByHowRecent(rawTimestamp) {
var currentDate = new Date();
//reference times for different displays
var ref = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0);
var refday = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0);
var refdayNext = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0);
var refweek = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0);
refday.setDate(ref.getDate() - 1);
refdayNext.setDate(ref.getDate() + 1);
refweek.setDate(ref.getDate() - 7);
var tdb = new Date(rawTimestamp);
// MAKE SURE API/PHP RETURNS THE TIME AS $row['time_settle'] = date('j/n/Y',strtotime($row['time_settle']));
//console.log(tdb)
//adjust to time zone
tdb.setMinutes(tdb.getMinutes());
//date format
if (tdb > ref && tdb < refdayNext) {
var hours = tdb.getHours();
var min = tdb.getMinutes();
if (min < 10) {
min = "0" + min;
}
if (hours == 0) {
var ampm = "AM";
} else if (hours < 12) {
var ampm = "AM";
} else if (hours == 12) {
var ampm = "PM";
} else {
hours -= 12;
var ampm = "PM";
}
var timeinsert = hours + ":" + min + " " + ampm;
} else if (tdb > refday && tdb < refdayNext) {
var timeinsert = "Yest";
} else if (tdb > refweek && tdb < refdayNext) {
var weekday = ["Sun", "Mon", "Tues", "Wedn", "Thur", "Fri", "Sat"][tdb.getDay()];
var timeinsert = weekday;
} else {
var timeinsert = tdb.getDate() + "/" + (tdb.getMonth() + 1) + "/" + tdb.getFullYear().toString().substr(2, 2);
}
return timeinsert;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment