I have method that gets as a time string "15:35". That time is in UTC TimeZone. But I wanna convert it to different TimeZone example(America/New_York or ...) . The examples say that there is a package that is "moment" that has "tz" method but I check that is no in that package. Also I mustn't update package or install one. How could i convert given time to according to given timezone without parsing?
Example : Given "18:35" in UTC -> Expected 14:35 in America/New_York
CodePudding user response:
I suggest that you should use moment because it's very easy to use if compared to pure javascript/typescript.
You can use the below method to do it:
moment.tz.setDefault(String)
In your case, you can set the timezone to America/New_York by:
moment.tz.setDefault("America/New_York")
You can find out more at https://momentjs.com/timezone/docs/#/using-timezones/default-timezone/
CodePudding user response:
I don't really understand why you can't install a package. If you are able to use moment.js (which I would recommend) and your string is no date string (like "2021-09-22T15:35:00Z") you could solve it like that:
function changeDatetimeByTimezone(datetime, timezone) {
const parsedDateAsUtc = moment.utc()
.startOf('day')
.add(datetime.substring(0, 2), "hours")
.add(datetime.substring(3, 5), "minutes");
return parsedDateAsUtc.clone().tz(timezone).format("hh:mm");
}
and then use it like this:
const dateTimeNY = changeDatetimeByTimezone("15:35", "America/New_York"); // 11:35
const dateTimeBE = changeDatetimeByTimezone("15:35", "Europe/Berlin"); // 17:35
CodePudding user response:
Install moment-timezone package. It will help to convert time. Refer below link.
https://momentjs.com/timezone/
How to use:
1.Import both below packages in top of your component file.
import moment from "moment";
import 'moment-timezone';
2.Convert the time as follows.
var localTime = moment.utc('18:35', "HH:mm").tz('America/New_York').format("HH:mm");
console.log(localTime);