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');
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');
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.
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}`);