2

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 time zone, when I need to keep like I received.

Any way to disable converting time to local timezone in DayJS?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Alex
  • 455
  • 1
  • 5
  • 14

2 Answers2

6

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.

Filip Huhta
  • 2,043
  • 7
  • 25
1

You can use the utc plugin.

import dayjs from "dayjs";
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc)


const dateTime = "2023-02-13T09:00:00.000-05:00";
const value = dayjs.utc(dateTime).format('h:mm A');

console.log(value);