Replies: 1 comment 1 reply
|
The right tool here is constructor(...args) {
super();
if (args.length > 1 && typeof args[args.length - 1] === "string") {
this.timeZone = args.pop();
}
...
} else if (typeof args[0] === "string") {
this.setTime(+new Date(args[0]));
}
...
}With a single string argument, Since your offsets vary per record ( import { TZDate } from "@date-fns/tz";
import { format } from "date-fns";
function toOriginalOffsetDate(isoString) {
const match = isoString.match(/([+-]\d{2}:\d{2}|Z)$/);
const offset = match ? (match[1] === "Z" ? "+00:00" : match[1]) : undefined;
return new TZDate(isoString, offset);
}
const departure = toOriginalOffsetDate("2025-02-01T08:30:00-05:00");
const arrival = toOriginalOffsetDate("2025-02-01T11:42:00-06:00");
format(departure, "h:mm a"); // "8:30 AM"
format(arrival, "h:mm a"); // "11:42 AM"This works no matter what zone the code runs in (Paris, a server in UTC, whatever), because If you'd rather not regex the string yourself, |
Uh oh!
There was an error while loading. Please reload this page.
I need to display departure and arrival times of a flight from New York (UTC-5) to Dallas (UTC-6) and I am currently in Paris (UTC+1). The dates come from an API as ISO formatted with an offset:
{ "departure_dt": "2025-02-01T08:30:00-05:00", "arrival_dt": "2025-02-01T11:42:00-06:00" }On the screen I should see respectively:
And not something like
What is the intended way dealing with this in
date-fns? I have only found suggestions to manually cut off the offset in the string.All reactions