Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent date conversion to local time zone with DayJS

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?

like image 244
kkkkkkkkkkkkkkkkk Avatar asked Dec 29 '25 07:12

kkkkkkkkkkkkkkkkk


2 Answers

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.

like image 154
Filip Huhta Avatar answered Dec 31 '25 23:12

Filip Huhta


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);
like image 22
Emeka Nwachukwu Avatar answered Jan 01 '26 00:01

Emeka Nwachukwu