JavaScript Date Time YYYY MM DD HH MM SS
Category:
Robot: "What time is it JavaScript, buddy? And when you answer, it better be in the format of 'YYYY-MM-DD HH:MM:SS' in 24 hour format with preceeding zeros on the month, day, hour, minute and second, or else!"
Me: "Relax big guy, just call this function, friend."
function js_yyyy_mm_dd_hh_mm_ss () { now = new Date(); year = "" + now.getFullYear(); month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; } day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; } hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; } minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; } second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; } return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; }
Here is an example usage:
alert(js_yyyy_mm_dd_hh_mm_ss()); // example alert message: 2011-05-18 15:20:12
Comments
ahren (not verified)
Wed, 07/04/2012 - 22:34
Permalink
Oops, you may not get quite
Oops, you may not get quite what you expected! Check your return string. Hint: HH:MM:SS
tyler
Wed, 07/04/2012 - 23:40
Permalink
Thanks for pointing that out,
Thanks for pointing that out, I have adjusted the code to show : instead of -
Jason (not verified)
Thu, 06/27/2013 - 03:07
Permalink
Wow... that's a lot of
Wow... that's a lot of Javascript code for something that should be really simple. Wish there was something like now = new Date('Y-m-d H:m:S');
tyler
Sat, 08/03/2013 - 00:35
Permalink
Yeah, it is a bummer there
Yeah, it is a bummer there isn't something like PHP date string handling in JS. There probably is, somebody just needs the motivation to type it in to Google. I myself am too tired, for now.
Vinci mini CAD (not verified)
Thu, 11/28/2013 - 09:36
Permalink
There is a simple, javascript
There is a simple, javascript implementation of date format, consistent with java standard: http://llamalab.com/js/date/Date.js
Vineet Kumar Arya (not verified)
Thu, 01/30/2014 - 05:29
Permalink
Very helpful !!!
Very helpful !!!
Ankit (not verified)
Wed, 05/13/2015 - 06:00
Permalink
HI What if i need the time in
HI What if i need the time in AM and PM format.
tyler
Wed, 05/13/2015 - 11:06
Permalink
You'll have to use a mod
You'll have to use a mod operator of 12 on the hours, and expand the function to accommodate that accordingly.