how do i get the current date and time from windows timezones - javascript

I have the following timezones:
when a user selects a timezone from the list how do i get whats the current time and date at that timezone? for example if i choose "Azores" i want to get the current date time for that area.
In moment i could use IANA timezones and pass the timezone like and format it to ("dddd, D MMM YYYY" )
moment().tz().guess;
but the user doesnt want to use IANA Timezones because they cant find some of the countries so i cant go with that option.
Is there a way i can determine the current datetime based on the timezones specified?
i also tried the following if i passed in the offset but that didnt work example:
moment().utcOffset("-01:00");
because its taking my local time and offsetting it so it doesnt give me the actual current datetime.

To get all available timezones:
How to get list of all timezones in javascript
const arr = Intl.supportedValuesOf('timeZone');
JS Date object is in UTC, so to get Date with timezone offset you can use
I want to get New York time in this JavaScript clock?
const date = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));

Related

How to display times in different time zones using the offset value

I am trying to display the current moment in different time zones. I have tried to use native javascript and the moment-js package but it seems you require the time zone name (ex. "America/Toronto") to display the information I want. The problem is that the information I currently have is the timestamp in string format (see below for string format) from the desired timezone, and the city the timestamp belongs to. The problem with using the city to create my tz value is that one of the cities I want to display isn't in the IANA tz database (Calgary).
String timestamp:
2022-04-26T14:19:42.8430964-04:00
As can be seen I do have the time offset and I was hoping there was a way to convert this string in js to a Date object and then display the time using the offset in the correct time zone.
Note what I want to display is the following format:
12:19 pm MT
I know I could just parse out the string but I feel like this isn't the best practice, however I may be wrong.
Also note that I will have to get the time zone (ex. MT, ET it can also be MST, EST) using the offset.
you don't need moment here. JS can do this natively. Also moment is now deprecated.
Your IANA timezone is America/Edmonton. So it's simple to do. That date format is an ISO 8601 date format, so you can just pass it into the new Date constructor and it'll parse it correctly:
const iso8601 = '2022-04-26T14:19:42.8430964-04:00';
const date = new Date(iso8601);
console.log(date.toLocaleString('en-US', { timeZone: 'America/Edmonton' }));
It doesn't matter what timezone your input date is set, so long as it has the correct offset in the ISO date. Once it's a Date, the offset is irrelevant. E.g.:
const iso8601 = '2022-04-26T14:19:42.8430964Z';
const date = new Date(iso8601);
//time will now be 4 hours off above as the input date is UTC
console.log(date.toLocaleString('en-US', { timeZone: 'America/Edmonton' }));

Local time zone not displayed while formatting OffsetDataTime using moment js [duplicate]

What is the best way to get client's timezone and convert it to some other timezone when using moment.js and moment-timezone.js
I want to find out what is clients timezone and later convert his date and time into some other timezone.
Does anybody has experience with this?
When using moment.js, use:
var tz = moment.tz.guess();
It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.
It is documented here.
Internally, it first tries to get the time zone from the browser using the following call:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.
If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.
var timedifference = new Date().getTimezoneOffset();
This returns the difference from the clients timezone from UTC time.
You can then play around with it as you like.
All current answers provide the offset differece at current time, not at a given date.
moment(date).utcOffset() returns the time difference in minutes between browser time and UTC at the date passed as argument (or today, if no date passed).
Here's a function to parse correct offset at the picked date:
function getUtcOffset(date) {
return moment(date)
.subtract(
moment(date).utcOffset(),
'minutes')
.utc()
}
Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/
i notice they also user their own library in their website, so you can have a try using the browser console before installing it
moment().tz(String);
The moment#tz mutator will change the time zone and update the offset.
moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z'); // +01:00
This information is used consistently in other operations, like calculating the start of the day.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format(); // 2013-11-18T11:55:00-05:00
m.startOf("day").format(); // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format(); // 2013-11-18T00:00:00+01:00
Without an argument, moment#tz returns:
the time zone name assigned to the moment instance or
undefined if a time zone has not been set.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz(); // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined; // true
You can also get your wanted time using the following JS code:
new Date(`${post.data.created_at} GMT+0200`)
In this example, my received dates were in GMT+0200 timezone. Instead of it can be every single timezone. And the returned data will be the date in your timezone. Hope this will help anyone to save time
if the user's timezone is all you wanted then
const localtz = moment.tz.guess() // returns user's timezone
Additionally if you wanted to use it then the best way to convert a timestamp to user's timezone is
const time = moment.tz(response.timestamp)
const localtz = moment.tz.guess() // user's timezone
const date = time.clone().tz(localtz) // convert time to user's timezone
here localtz is the user's timezone and using it we can convert the timestamp to user's local time
First, you can find out the clients time zone using the following
let zoneVal = moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('Z')
it will return you the GMT zone format for example +5:30 (colombo/srilanka & Delhi/India) or +6:00(Dhaka Bangladesh) depending on the region you are in.
secondly,
if you want to find out the time of a particular time zone , then do the following
moment.tz("Asia/Dhaka").format()
which will return you the time zone value in ISO format of Dhaka.
Using moment timezone you can get easily your local date-time
moment().utcOffset(0, true).format()

constructing a date object along with time zone

I want to construct a Date object along with dynamically selected timezone. I am currently in IST time zone. I want to eliminate the usage of Date.parse() as it does not behave as expected at times.
let's assume tzOffset to be +05:30 for now. It could be any other timezone based on what users want. new Date(epochDate).toISOString(); converts the date to UTC timezone. How do I get the date in toISOString() format but also get it in the desired time zone
const tsConstruct = `${year}-${month}-${date}T${hour}:${min}:00${tzOffset}`;
const epochDate = Date.parse(tsConstruct);
scheduledTs = new Date(epochDate).toISOString();
JavaScript's Date does not store timezone info. It just stores the number of milliseconds from UNIX EPOCH. Then, depending if you use the UTC methods or not, it returns the date and time in UTC or the local time.
You should have to change the date and time, based on the timezone indicated, to UTC or local time, and then store it in a Date object. But, of course, to show the stored time in another timezone different to the local one or UTC, you must do the conversions yourself, so, as #RuChengChong suggested, use a helper library like momentjs.

.tz() in moment.js timezone does not convert time zones correctly

I am having trouble when converting from time zone to time zone using moment.js.
This is my code:
convertSelectedTimeZoneToClients() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let con = this.$rootScope.mtz.tz(utcTime, timeZoneInfo.usersTimeZone).format();
return con;
}
The user picks date, time and time zone from drop downs on client page.
In timeZoneInfo object I am storing usersTimeZone (I want to be able to convert timezone that user selected on page and convert it to his local time zone).
For example user picks: 11/08/2016 01:30 and UTC+2 timezone and his timezone is UTC+1, than I want to show him in label: That is 11/08/2016 00:30 since UTC+1 is -1 hour comparing to UTC+2 timezone.
I store offsets for time zones in one object and those values are hard coded (utcOffset: this.formData.timeZone.offset).
Before I convert time form time zone to time zone I do this: get time zone -> convert to UTC time -> convert to user time zone.
What is happening is that utcTime variable has correct value. But when I pass that value and users time zone to .tz() function and using format() to get some readable value I get same time as utcTime like shown in picture:
I have read moment.js docs and by them this .tz().format() should do the work, but as you can see my result is: 2016-11-08T23:30:00+01:00.
So it gets that is should be incremented by 1 hour but how to accomplish to get: 2016-11-09T00:30 instead?
I have tried .format("YYYY-MM-DD HH:mm") as well same problem. When I use .local() function that should convert from utc time to specified time zone same problem is present.
Am I getting something wrongly? I am pretty sure that when you convert from 2016-11-08T23:30 UTC to UTC+1 it should be 2016-11-09T00:30, or one hour forward. Does someone sees something strange in this code?

Time Zone Offset Calculations

Let's suppose the server gives the date in this format:
var date = '2012-08-08T15:04:33+0200';
As you can see the previous date has a Timezone offset of two hours.
Let's suppose I need to display the same date in different places having different timezone.
What is the proper way to display the date in different clients having the different time zone using moment.js
I did try the following but I am not sure because I cannot test it.
moment(date, "YYYY-MM-DDTHH:mm:ss").fromNow();
According the documentation it should be enough just passing the following parameter ´Z´ or ZZ according your date format.
So in your case it should be:
var date = '2012-08-08T15:04:33+0200';
moment(date, "YYYY-MM-DDTHH:mm:ssZ").fromNow();

Categories