Tutorial :how to get formatted date time like 2009-05-29 21:55:57 using javascript?



Question:

when using new Date,I get something like follows:

Fri May 29 2009 22:39:02 GMT+0800 (China Standard Time)

but what I want is xxxx-xx-xx xx:xx:xx formatted time string


Solution:1

Although it doesn't pad to two characters in some of the cases, it does what I expect you want

function getFormattedDate() {      var date = new Date();      var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();        return str;  }  


Solution:2

jonathan's answers lacks the leading zero. There is a simple solution to this:

function getFormattedDate(){      var d = new Date();        d = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2) + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2) + ":" + ('0' + d.getSeconds()).slice(-2);        return d;  }  

basically add 0 and then just take the 2 last characters. So 031 will take 31. 01 will take 01...

jsfiddle


Solution:3

it may be overkill for what you want, but have you looked into datejs ?


Solution:4

What you are looking for is toISOString that will be a part of ECMAScript Fifth Edition. In the meantime you could simply use the toJSON method found in json2.js from json.org.

The portion of interest to you would be:

Date.prototype.toJSON = function (key) {    function f(n) {      // Format integers to have at least two digits.      return n < 10 ? '0' + n : n;    }    return this.getUTCFullYear()   + '-' +         f(this.getUTCMonth() + 1) + '-' +         f(this.getUTCDate())      + 'T' +         f(this.getUTCHours())     + ':' +         f(this.getUTCMinutes())   + ':' +         f(this.getUTCSeconds())   + 'Z';  };  


Solution:5

Try this.

var datetime = new Date().toJSON().slice(0,10)       + " " + new Date(new Date()).toString().split(' ')[4];    console.log(datetime);  


Solution:6

You can use the toJSON() method to get a DateTime style format

var today = new Date().toJSON();   // produces something like: 2012-10-29T21:54:07.609Z  

From there you can clean it up...

To grab the date and time:

var today = new Date().toJSON().substring(0,19).replace('T',' ');  

To grab the just the date:

var today = new Date().toJSON().substring(0,10).replace('T',' ');  

To grab just the time:

var today = new Date().toJSON().substring(10,19).replace('T',' ');  

Edit: As others have pointed out, this will only work for UTC. Look above for better answers.


Solution:7

Date.prototype.toUTCArray= function(){      var D= this;      return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),      D.getUTCMinutes(), D.getUTCSeconds()];  }    Date.prototype.toISO= function(t){      var tem, A= this.toUTCArray(), i= 0;      A[1]+= 1;      while(i++<7){          tem= A[i];          if(tem<10) A[i]= '0'+tem;      }      return A.splice(0, 3).join('-')+'T'+A.join(':');      // you can use a space instead of 'T' here  }    Date.fromISO= function(s){      var i= 0, A= s.split(/\D+/);      while(i++<7){          if(!A[i]) A[i]= 0;          else A[i]= parseInt(A[i], 10);      }      --s[1];      return new Date(Date.UTC(A[0], A[1], A[2], A[3], A[4], A[5]));    }       var D= new Date();     var s1= D.toISO();     var s2= Date.fromISO(s1);     alert('ISO= '+s1+'\nlocal Date returned:\n'+s2);  


Solution:8

The Any+Time(TM) JavaScript Library's AnyTime.Converter object easily converts a JS Date object into ISO or virtually any other format... in fact, the format you want is the default format, so you could simply say:

(new AnyTime.Converter()).format(new Date());  


Solution:9

Just another solution: I was trying to get same format( YYYY-MM-DD HH:MM:SS ) but date.getMonth() was found inaccurate. So I decided to derive the format myself.

This code was deployed early 2015, and it works fine till date.

var m_names =["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];    var d = new Date();  var spl = d.toString().split(' ');  var mnth = parseInt(m_names.indexOf(spl[1])+1).toString();  mnth = (mnth.length == 1) ? '0'+mnth : mnth          //  yyyy   -   mm   -   dd       hh:mm:ss   var data = spl[3]+'-'+mnth+'-'+spl[2]+' '+spl[4]  alert(data)  

Test the code in JSFIDDLE


Solution:10

Converting Milliseconds to date formate using javascript

- for reference see below jsfiddle

http://jsfiddle.net/kavithaReddy/cspn3pj0/1/

function () {     var values = "/Date(1409819809000)/";     var dt = new Date(parseInt(values.substring(6, values.length - 2)));     var dtString1 = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();     alert(dtString1);  })();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »