简体   繁体   中英

Transform date to wire format (YYYY-MM-DD) in javascript

Having this input: Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time) , is there a way to format it as YYYY-MM-DD, to it will become 2021-02-03 ?

Try this:

 const date = moment(new Date('Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)')).format('YYYY-MM-DD'); console.log(date);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

Parsing a timestamp to a date to reformat it may well produce incorrect results if the timestamp includes an offset or timezone. Given "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)", for a user with an offset of +1 or less the date will be 2 Feb, not 3 Feb.

The most reliable method is to reformat the string, eg

 let timestamp = "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)"; let months = [,'Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']; let pad = n=>('0'+n).slice(-2); let p = timestamp.split(' '); console.log(`${p[3]}-${pad(months.indexOf(p[1]))}-${p[2]}`);

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