Skip to content

Instantly share code, notes, and snippets.

@englishextra
Forked from hurjas/timestamp.js
Created December 20, 2016 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save englishextra/c10c903ef93c84b3269f1560b448f7a9 to your computer and use it in GitHub Desktop.
Save englishextra/c10c903ef93c84b3269f1560b448f7a9 to your computer and use it in GitHub Desktop.
Print out a nicely formatted timestamp in JavaScript.
/**
* Return a timestamp with the format "m/d/yy h:MM:ss TT"
* @type {Date}
*/
function timeStamp() {
// Create a date object with the current time
var now = new Date();
// Create an array with the current month, day and time
var date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ];
// Create an array with the current hour, minute and second
var time = [ now.getHours(), now.getMinutes(), now.getSeconds() ];
// Determine AM or PM suffix based on the hour
var suffix = ( time[0] < 12 ) ? "AM" : "PM";
// Convert hour from military time
time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12;
// If hour is 0, set it to 12
time[0] = time[0] || 12;
// If seconds and minutes are less than 10, add a zero
for ( var i = 1; i < 3; i++ ) {
if ( time[i] < 10 ) {
time[i] = "0" + time[i];
}
}
// Return the formatted string
return date.join("/") + " " + time.join(":") + " " + suffix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment