简体   繁体   中英

How to format hour and minutes in date-fns?

I'm migrating my code from MomentJS to date-fns and having the following issue when setting the hour and minutes.

This is my momentJS that works just fine:

var someDate = moment.utc('2020-07-16T16:35:39.955873Z')) // 2020-07-16T16:35:39.955Z
console.log(someDate.format('MM/DD/YYYY [ at ] LT ')); // 07/16/2020 at 4:35 PM

This is my code using date-fns :

var someTime = zonedTimeToUtc('2020-07-16T16:35:39.955873Z', 'utc'); // 2020-07-16T16:35:39.955Z
console.log(format(new Date(someTime), "MM/dd/yyyy 'at' h:mm a")); // 07/16/2020 at 10:35 AM

so, I want my date-fns code to print

07/16/2020 at 4:35 PM

but it's printing

07/16/2020 at 10:35 AM

Why is that? A simple way to get it to print the date that I want is by removing the "Z" from the value of someTime variable (like this: 2020-07-16T16:35:39.955), then it works, but I don't want to remove it manually. Can anyone tell me what I'm missing or doing wrong? Thanks a lot in advance!

Here's a LIVE DEMO

Try using utcToZonedTime()

To change the displayed date/time returned from format(), you must use either:

  • utcToZonedTime : when you want to know what the local date is in another timezone
  • zonedTimeToUtc : when you want to know what a date in another timezone is in the local timezone

Working Demo

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