JavaScript Date – How to Format Date Using JavaScript

datejavascript

have problem for format date in JavaScript, this is my function code

   //originalDate = '2016-03-02 09:12:14.989522';
   var d = new Date(originalDate),
        month = d.getMonth() + 1,
        day =d.getDate(),
        year = d.getFullYear(),
        hour = d.getHours(),
        min = d.getMinutes();
    alert([day, month, year].join('-')+' '+[hour,min].join(':'));

and my original date ='2016-03-02 09:12:14.989522';
and my code always return 'Nan-Nan-Nan Nan:Nan', It's seen unknown originalDate that I pass to.
any help?

Note: datatype in database of date of mine is timestamp

Best Answer

Simple solution: Replace the space in your date string with a "T".

(However, to be completely technically correct, you should also include a time zone indicator at the end, either an additional "Z" to indicate UTC, i.e. Coordinated Universal Time, or "+hh:mm" or "-hh:mm" to indicate a time zone offset.)

The MDN site for Date.parse() writes:

Because of the variances in parsing of date strings, ...results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

and

The date time string may be in ISO 8601 format.

The ISP 8601 specs referred to above writes:

The formats are as follows. Exactly the components shown here must be present, with exactly this punctuation. Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO 8601.

and

Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

Here is your code re-written replacing the space in date with a "T". If that doesn't work in your browser, add a "Z" or time zone offset at the end of date.

var date ='2016-03-02T09:12:14.989522';
var d = new Date(date),
  month = d.getMonth() + 1,
  day = d.getDate(),
  year = d.getFullYear(),
  hour = d.getHours(),
  min = d.getMinutes();
document.write([day, month, year].join('-') + ' ' + [hour, min].join(':'));