-
-
Save hurjas/2660489 to your computer and use it in GitHub Desktop.
Print out a nicely formatted timestamp in JavaScript.
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
/** | |
* 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; | |
} |
Thanks a lot!
cool, thanks for sharing your example!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Greetings, a more complete function using a more complete String replace function, use: mf("Y-M-D H:I:S")
Y=Complete Year
y=Two digits year
M=Month
D=Date
H:Hour
h:12 hour format
I: minutes
S:seconds
x:am/pm
function mf(formato){ var hor,hor2,x; var fechai=new Date(); var ano=fechai.getYear()+1900; var ano2=(""+(fechai.getYear()+1900)).slice(-2); var mes=("0"+(fechai.getMonth()+1)).slice(-2); var dia=("0"+fechai.getDate()).slice(-2); hor=hor2=("0"+fechai.getHours()).slice(-2); if(fechai.getHours()>12){ hor2=fechai.getHours()-12; x="pm"; }else{ x="am"; } var min=("0"+fechai.getMinutes()).slice(-2); var seg=("0"+fechai.getSeconds()).slice(-2); var fecha=formato.reemplaza("YyMDHhISx".split(''),[ano,ano2,mes,dia,hor,hor2,min,seg,x]); alert(fecha); } String.prototype.reemplaza=function(busca,reemplaza){ var b=Array.isArray(busca); var r=Array.isArray(reemplaza); var ret=this; if(b){ for(var i in busca){ var c=r?(reemplaza[i]?reemplaza[i]:""):reemplaza; ret=ret.replace(new RegExp(busca[i],'g'),c); } }else{ var c=r?reemplaza[0]:reemplaza; ret=ret.replace(new RegExp(busca,'g'),c); } return ret; }