I have a date string const someDate = 2023-02-13T09:00:00.000-05:00
The problem is when I'm formatting it via dayjs
dayjs(someDate).format('h:mm A')
It returns me string according to my local timezone, when I need to keep like I received. Any way to disable converting time to local timezone in dayjs?
CodePudding user response:
Yes!
You can disable converting to local timezone in dayjs by passing in the original timezone as an additional argument in the dayjs constructor.
Example:
const someDate = "2023-02-13T09:00:00.000-05:00";
const originalTimezone = someDate.slice(-6);
const formattedDate = dayjs(someDate).utcOffset(originalTimezone).format('h:mm A');
The utcOffset()
method allows you to set the offset in minutes from UTC for a specific date instance. The originalTimezone
constant is used to extract the timezone offset (-05:00)
from the original date string someDate
, and pass it to the utcOffset()
method. This will ensure that the formatted date stays in the original timezone.