简体   繁体   中英

How to convert string date to specific format?

I am trying to get date from string in specific format like:

 const format = 'MM/dd/yyyy HH:mm'; const dt = "2021-03-11T22:00:00.000Z"; // expecting "03/11/2021 22:00" console.log(moment(dt).format(format)); // but getting "03/Th/yyyy 23:00"
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

I tried js date, moment, luxon and I don't understand how to make this:(
I suspect that 000Z made problem but this is date I get.

The difference between Moment.js and Luxon is the case of the format keys. Please review the key/token tables.

Note: Moment.js has been deprecated in favor of the team's newer library Luxon and other ECMA Script standards that are being introduced in ECMA-402 . If you are considering using Moment.js now, just switch over to Luxon.


If you are using Luxon, you can call .toUTC() right before you format the date. Make sure your day of month ( dd ) and year ( yyyy ) format keys are lower-case.

 const DateTime = luxon.DateTime; const format = 'MM/dd/yyyy HH:mm', dt = "2021-03-11T22:00:00.000Z"; console.log(DateTime.fromISO(dt).toUTC().toFormat(format)); // 03/11/2021 22:00
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>

If you are using Moment.js, you can call .utc() right before you format the date. Make sure your day of month ( DD ) and year ( YYYY ) format keys are upper-case.

 const format = 'MM/DD/YYYY HH:mm', dt = "2021-03-11T22:00:00.000Z"; console.log(moment(dt).utc().format(format)); // 03/11/2021 22:00
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Your format string is wrong, it should be: 'MM/DD/YYYY HH:mm' .

Then, if your date comes with ':000Z' , you should remove it with the substring() method.

Working code:

 const format = 'MM/DD/YYYY HH:mm'; const dateString = "2021-03-11T22:00:00:000Z"; const date = dateString.substring(0, dateString.length - 5); console.log(moment(date).format(format)); // prints 03/11/2021 22:00
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

You need to use YYYY instead of yyyy and DD instead of dd to get the expected result.
By the way, I suggest using another library than Moment , like dayjs for instance.

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