1

I have the date in this format:

Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

I want this string to be converted into this format:

 2016-11-15 00:00:00

I tried:

var s = startDate.format('YYYY-MM-DD HH:mm:ss');
jwpfox
  • 5,124
  • 11
  • 45
  • 42
RKR
  • 657
  • 3
  • 13
  • 26
  • RTFB - Read the foolish book - read the documentation! – user2182349 Dec 14 '16 at 02:51
  • Possible duplicate of [JS. Convert format date](http://stackoverflow.com/questions/17301721/js-convert-format-date) – LF00 Dec 14 '16 at 02:52
  • You'll need to show a bit of what you've tried in order for anyone to help you out here. – jonmrich Dec 14 '16 at 03:14
  • @jonmrich I am very sorry that I did not mention my code.Even though I got what I did was wrong and why it was wrong and the below two answers worked perfectly.Anyway I am new to Stack overflow so I am now only getting started how things work here and thank you for the guidance – RKR Dec 14 '16 at 05:07

2 Answers2

2

I would recommend using the library moment.js. This library was specifically designed to help with dates and formatting.

You simply need to do this:

let date = moment('Tue Nov 15 2016 00:00:00 GMT+0800').format('YYYY-MM-DD HH:mm:ss')
console.log(date)

However, there is a caveat. Since the date that you are providing is in a nonstandard format, you will get a deprecation warning, like this:

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

Basically, the solution is to provide a standard format for your date. The simplest way to do that is to either chop off the timezone, since it seems like you will be displaying the date assuming the TZ supplied is the local one.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
  • It was what I needed exactly! Thanks a lot (I have no reputation to upvote the answer but I made this as the correct answer. ) – RKR Dec 14 '16 at 05:07
2

You can get it done just using vanilla javascript:

const date = new Date('Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time');

const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();

const timeToHHMMSS = (hours, minutes, seconds) => {
  return [hours, minutes, seconds].map(value => {
    return ('0' + value).slice(-2);
  }).join(':');
}

const formattedDate = `${year}-${month}-${day}`;
const formattedTime = timeToHHMMSS(hours, minutes, seconds);

console.log(`${formattedDate} ${formattedTime}`);
pridegsu
  • 1,108
  • 1
  • 12
  • 27