ching
ching

Reputation: 142

format date using javascript

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

Upvotes: 1

Views: 870

Answers (3)

Mehdi Mehdi
Mehdi Mehdi

Reputation: 1

First parse your original date then use it in your code.

var MilliSecond=Date.parse(originalDate);
var d=new Date(MilliSecond),
month=d.getMonth()+1,
day=d.getDay(), .......

Upvotes: 0

Andrew Willems
Andrew Willems

Reputation: 12458

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(':'));

Upvotes: 1

Umar Ashraf
Umar Ashraf

Reputation: 192

Is the date parameter in your code a Date object? That won't work. There is no such constructor in Javascript. You could use date.now() though.

Check here for the valid constructors for Date https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

Related Questions