Reputation: 105
I pull data from a database and output JSON. Once of the items pulls a date entered in this format 2018-06-25
I tried this:
var date = new Date(element.rundate).toString().substring(0,15);
However the output subtracts a day like this Sun Jun 24 2018
Anyone know how to correct?
Upvotes: 0
Views: 100
Reputation: 21161
The problem is that when the date format is yyyy-mm-dd
, JavaScript will parse it as an ISO 8601 date, so it will assume it's UTC 00:00
.
However, if the date format is yyyy/mm/dd
or mm-dd-yyyy
it will use local time, according to the RFC 2822
:
The date and time-of-day SHOULD express local time.
Therefore, replacing dashes -
with slashes /
will do the trick. Alternatively, you can also split the different parts of the date and create a new date string representation with the format mm-dd-yyyy
, but I think the previous approach is more concise and cleaner:
// Original date:
const dashes = '2018-06-25';
// With slashes instead of dashes:
const slashes = dashes.replace(/-/g, '\/');
// mm-dd-yyyyinstead of dd-mm-yyyy:
const [ year, month, day ] = dashes.split('-');
const monthDayYear = `${ month }-${ day }-${ year }`;
// Output:
console.log(`${ dashes } => ${ new Date(dashes) }`);
console.log(`${ dashes } => ${ slashes } => ${ new Date(slashes) }`);
console.log(`${ dashes } => ${ monthDayYear } => ${ new Date(monthDayYear) }`);
Upvotes: 0
Reputation: 944
you can use moment.js or
const date = new Date(element.rundate)
result = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
Upvotes: 1