Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@benhopper1

This comment has been minimized.

Copy link

@benhopper1 benhopper1 commented May 15, 2014

Thanks, I converted it to my needs. Saved me much time.

@jesusmacedo

This comment has been minimized.

Copy link

@jesusmacedo jesusmacedo commented Oct 9, 2014

It's really nice, thanks! 👍

@chkarypidis

This comment has been minimized.

Copy link

@chkarypidis chkarypidis commented Jan 23, 2015

Thanks. This saved me a couple of minutes so I decided to spent them on dropping a line to say cheers :-)

@alexhidalgo

This comment has been minimized.

Copy link

@alexhidalgo alexhidalgo commented Feb 28, 2015

Thanks @hurjas

@pabli44

This comment has been minimized.

Copy link

@pabli44 pabli44 commented Apr 16, 2015

Thanks a lot, Its working , thanks !!

@swogger

This comment has been minimized.

Copy link

@swogger swogger commented Jul 3, 2015

(new Date).toISOString();
"2015-07-03T10:49:26.892Z"

(new Date).toISOString().replace(/z|t/gi,' ');
"2015-07-03 10:50:22.481 "

(new Date).toISOString().replace(/z|t/gi,' ').trim();
"2015-07-03 10:50:31.112"

@randseay

This comment has been minimized.

Copy link

@randseay randseay commented Aug 27, 2015

Coming late to the party, but this snippet was helpful to me... So thanks!

I think you should be able to save a step if you test for the hour being greater than or equal to 12 when converting from military time.

// 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;    <--- No longer needed
@aehven

This comment has been minimized.

Copy link

@aehven aehven commented Sep 18, 2015

Very nice.

I needed a compact date/time format -- don't care about seconds, don't care about other centuries -- so I modified the top lines to look like the following. If no options are give, it works as original.

function timeStamp(options) {
  options = typeof options !== 'undefined' ? options : {};

// 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() ];
  if(options.compactDate) {
    date.push(now.getFullYear()-2000);
  }
  else {
    date.push(now.getFullYear());
  }

// Create an array with the current hour, minute and second
  var time = [ now.getHours(), now.getMinutes() ];
  if(!options.compactTime) {
    time.push(now.getSeconds());
  }

// Determine AM or PM suffix based on the hour
.
.
.

When I call it with timeStamp({compactTime:true, compactDate:true}) I get something like "9/18/15 4:18 PM".

@carlbrockwell

This comment has been minimized.

Copy link

@carlbrockwell carlbrockwell commented Jan 10, 2016

Thanks for this, was very helpful

@dprothero

This comment has been minimized.

Copy link

@dprothero dprothero commented Jun 13, 2016

👍

@steven160505

This comment has been minimized.

Copy link

@steven160505 steven160505 commented Jun 14, 2016

Thanks!

@WectonicG

This comment has been minimized.

Copy link

@WectonicG WectonicG commented Jun 27, 2016

good job!! 👍

@GeniusAnimus

This comment has been minimized.

Copy link

@GeniusAnimus GeniusAnimus commented Aug 14, 2016

hwo do I call this into a string?

@ColinStuart-minted

This comment has been minimized.

Copy link

@ColinStuart-minted ColinStuart-minted commented Aug 29, 2016

Super helpful, thanks!

@calazarin

This comment has been minimized.

Copy link

@calazarin calazarin commented Sep 23, 2016

Thank you a lot!

@rrundle

This comment has been minimized.

Copy link

@rrundle rrundle commented Dec 1, 2016

Huge help! Cheers!

@webdeveloperninja

This comment has been minimized.

Copy link

@webdeveloperninja webdeveloperninja commented Feb 25, 2017

Thanks

@JonnathanCalderon

This comment has been minimized.

Copy link

@JonnathanCalderon JonnathanCalderon commented May 2, 2017

Nice! ;)

@dannysofftie

This comment has been minimized.

Copy link

@dannysofftie dannysofftie commented Jun 4, 2017

Just what I needed.... hugs!!!

@elgindavis

This comment has been minimized.

Copy link

@elgindavis elgindavis commented Aug 6, 2017

Works great! Thanks!

@kannieWeesNie

This comment has been minimized.

Copy link

@kannieWeesNie kannieWeesNie commented Nov 18, 2017

Thanks! Works great. Saved me some time.

@174n

This comment has been minimized.

Copy link

@174n 174n commented Jan 17, 2018

function timeStamp() {
// Create a date object with the current time
  let now = new Date();

// Create an array with the current month, day and time
  let date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ].map(d=>d.toString().length === 1 ? "0"+d : d);

// Create an array with the current hour, minute and second
  let time = [ now.getHours(), now.getMinutes(), now.getSeconds() ].map(d=>d.toString().length === 1 ? "0"+d : d);


// Return the formatted string
  return time.join(":") + " " + date.join(".");
}
@jeen-github

This comment has been minimized.

Copy link

@jeen-github jeen-github commented Feb 1, 2018

Thanks Rundik.

@alxalm

This comment has been minimized.

Copy link

@alxalm alxalm commented Feb 1, 2018

Me like it too!

@NeaIon

This comment has been minimized.

Copy link

@NeaIon NeaIon commented Feb 21, 2018

Great!

@david007co

This comment has been minimized.

Copy link

@david007co david007co commented Apr 14, 2018

Extremely handy. Thanks!!

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented May 15, 2018

been super useful! created a fiddle using a variation of @Rundik's code.

@keithpjolley

This comment has been minimized.

Copy link

@keithpjolley keithpjolley commented Jun 20, 2018

Here's similar using built-ins. I think it may be more portable while still achieving the same goals, except it's yyyy instead of yy, but I much prefer yyyy anyways.

> function timeStamp(date, locale) {
  const event = (date===undefined) ? new Date() : new Date(date);
  return event.toLocaleDateString(locale) + " " + event.toLocaleTimeString(locale)
};

> timeStamp() // no args gives current date+time in users locale (e.g. en-us, PDT)
6/20/2018 2:06:31 PM
> timeStamp(0) // date input can be various formats
12/31/1969 4:00:00 PM
> timeStamp("7/4/1776 6:00 AM", 'en-gb') // give date+time in other locales
04/07/1776 06:00:00
> timeStamp("7/4/1776 6:00 AM", 'en-us') // force the og format in other locales
7/4/1776 6:00:00 AM
> timeStamp(new Date(), 'en-us') // current date in og format even in different locales
6/20/2018 2:06:31 PM
@seox

This comment has been minimized.

Copy link

@seox seox commented Aug 29, 2018

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; }

@IceBotYT

This comment has been minimized.

Copy link

@IceBotYT IceBotYT commented Nov 29, 2020

Thanks a lot!

@IsabelMeraner

This comment has been minimized.

Copy link

@IsabelMeraner IsabelMeraner commented Oct 6, 2021

cool, thanks for sharing your example!

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