Reputation: 5678
I'm trying to parse a string representing a UTC date and then log it to NY timezone. The issue I'm having is that the date / time string is being parsed as Eastern Time (my local timezone), rather than UTC time.
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
const dateString = "7/1/2023 08:04:09 AM";
const myDate = dayjs.utc(dateString);
const utcDateString = myDate.utc().format('MM/DD/YYYY HH:mm:ss');
const formattedString = myDate.tz("America/New_York").format('MM/DD/YYYY HH:mm:ss');
console.log(utcDateString) // 07/01/2023 12:04:09
console.log(formattedString) // 07/01/2023 08:04:09
As you can see, dayjs is parsing dateString
as a local date.
The result I expect is utcDateString
to be the same as dateString
and for formattedString
to be 4:04:09 AM
Upvotes: 2
Views: 4404
Reputation: 53
First of all, just let me clarify what I have understood from your question:
myDate
represent the date you convert from dateString
base from your local timezone,utcDateString
represent the date you convert from myDate
to utc dateformattedString
represent the date from myDate
converting to another time zoneHere are my findings based on the issue you had:
it looks like there is a specific format expected when we use dayjs.utc
function, I am not 100% sure about the expected formats exactly are, but if we try to pass the format that we are using (in your case,it would be something like DD/MM/YYYY HH:mm:ss A
), by passing an extra parameter, we are able to let dayjs know more about the date that you want to convert into local time, myDate
.
Solution
replace this line var myDate = dayjs.utc(dateString);
to be:
var inputDateFormat='DD/MM/YYYY HH:mm:ss A';
var myDate = dayjs.utc(dateString,inputDateFormat);
Hope this would help!
Enjoy :)
Upvotes: 0