49

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

omg
  • 136,412
  • 142
  • 288
  • 348

11 Answers11

62

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;
}
mauris
  • 42,982
  • 15
  • 99
  • 131
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
43

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

Toskan
  • 13,911
  • 14
  • 95
  • 185
  • This works great, and it solves the problem of converting any to any timezone in this format by using, for example `getFormattedDate( new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"})));`. Substituting "T" for the " " in the formatted string gives you the format that is used in Microsoft Graph and other places that use the JSON date format without a timezone in the date string itself. – RealHandy Aug 20 '19 at 19:40
  • @RealHandy that is to support time zones? I don't see a 'T' in the output. Or are you talking about the part of `.toLocaleString("en-US", {timeZone: "America/New_York"})` to remove the T? – Toskan Aug 20 '19 at 20:20
  • Sorry, I wasn't clear there. As is, the output format would be `xxxx-xx-xx xx:xx:xx`, but for MS Graph (JSON-esque with no Z at the end) date format, you need `xxxx-xx-xxTxx:xx:xx` (I assume the T means _time_, since that's what comes after the T) – RealHandy Aug 21 '19 at 17:35
13

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.

Note: At the time of this edit, this is pretty popular: date-fns.org

UPDATE

There are now plenty of getters on the Date.prototype but just for the sake of fun code, here are some slick new moves:

const today = new Date().toJSON();
const [date, time] = today.split('T')
const [year, month, day] = date.split('-')
const [hour, minutes, secondsTZ] = time.split(':')
const [seconds, timezone] = secondsTZ.split('.')
jiminikiz
  • 2,867
  • 1
  • 25
  • 28
  • 1
    It's very useful. But it gives the time in UTC. not the local time – Firnas Dec 20 '15 at 06:47
  • 1
    This gives incorrect date if users local time is not UTC and the time of day is less than the timezone offset. i.e.: for following date: `Mon May 01 2017 00:00:00 GMT+0200` it gives `2017-04-30 22:00:00` – SWilk Apr 21 '17 at 13:12
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';
};
Mister Lucky
  • 4,053
  • 2
  • 20
  • 18
3

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

mkoryak
  • 57,086
  • 61
  • 201
  • 257
2

Try this.

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

console.log(datetime);
Angel Koh
  • 12,479
  • 7
  • 64
  • 91
Moshood Awari
  • 500
  • 4
  • 5
0

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);
})();
Satheesh
  • 10,998
  • 6
  • 50
  • 93
kavitha Reddy
  • 3,303
  • 24
  • 14
0

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

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46
0

Modernised version of @Toskan's answer:

const getFormattedDate = (d = new Date()) => 
   d.getFullYear() + "-" +
   (d.getMonth() + 1).toString().padStart(2, '0') + "-" +
   d.getDate().toString().padStart(2, '0') + " " +
   d.getHours().toString().padStart(2, '0') + ":" +
   d.getMinutes().toString().padStart(2, '0') + ":" +
   d.getSeconds().toString().padStart(2, '0');

console.log(getFormattedDate());   //  2022-07-28 12:44:44
ellockie
  • 3,730
  • 6
  • 42
  • 44
0
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);
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

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());
Andrew M. Andrews III
  • 1,989
  • 18
  • 23