简体   繁体   中英

How to convert json date record with javascript

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?

you can use moment.js or

const date = new Date(element.rundate)
result = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM