Original code
const start = new Date();
console.log(start);
Result
2023-12-14T20:11:12.388Z
My timezone is America/New_York
, 5 hours behind UTC.
Question
How should i convert a new Date
object in the format of?
2023-12-14T15:11:12-05:00
I’ve been trying things like this but no luck yet,
const dateFormat = new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
dateStyle: "short",
timeStyle: "long"
});
console.log(dateFormat);
Either native JS, or date-fns is fine.
5
Answers
Seems
formatISO
from date-fns works:You can use
date-fns-tz
.npm install date-fns-tz
I’m not necessarily thrilled with the fact that JavaScript is somewhat underpowered when it comes to handling dates.
Solution # 1 (
function convertToTimeZone(Date, string): Date
)If you retrieve the date from your machine and convert it to a specific language’s date, you get the correct time back, but in a textual form. To turn it back into a Date object, you have to redeclare it. The solution is, by the way, native JavaScript, so it might be a bit more practical than installing a complete package just for this.
Solution # 2 (
new Date().toTimeZone(string): Date
)Alternatively, we have the option to extend the original Date class. While in the solution, I’ll start from the original timestamp, I will declare a new class, this time corresponding to the timestamp but in the desired time zone.
You don’t really need to use a library for this.
You can achieve this simply by: