How to get client side timezone id in JavaScript? - javascript

I need to get client side timezone using JavaScript. I am using below code.
new Date().toString().split('(')[1].slice(0, -1)
But it returns timezone daylightname, and I need id.
For example, client side timezone as set as (UTC-05:00) Eastern Time (US & Canada) and I need to get output as Eastern Standard Time. But I am getting Eastern Daylight Time as output.
Can I do this without any additional plugin requirements?

Try the following
var objdatetime = new Date();
var timezone = objdatetime.toTimeString();
var tzstr = timezone.split("(");
var timezoneid = tzstr[1].toString().replace(")","");
alert(timezoneid);

How about this?
new Date().toString().split('(')[1].slice(0, -1).replace('Daylight', 'Standard')

Related

Javascript displaying incorrect date

Im currently testing out running a server with routes etc. and am trying to display the date of the previous person to request that route. Usually when i use the new Date() object i get it in my local time, but for some reason it is displaying it in UTC (coordinated universal time) and im not sure how to change it.
my code is
var date;
var dateArr = [];
var counter = 0;
router.get('/last.txt', function(req, res) {
counter++;
date = new Date().toString();
dateArr.push(date);
if (counter == 1) {
res.send("");
} else {
res.send(dateArr[counter-1]);
}
});
but i keep receiving the date in the format:
Fri Mar 26 2021 07:24:50 GMT+0000 (Coordinated Universal Time)
Any advice would be appreciated!
EDIT: I live in Australia so i think it usually outputs in AEDT
It would appear that UTC is the timezone in place for the server where this code is running. That's fine, you can convert that to the local timezone on the client quite easily. Rather than using toString, though, I would store either the Date object, or its time value (the result of .valueOf()), or the result of .toISOString() and then send either the time value (a number) or the ISO string value to the client. That way, you're not relying on the timezone of the server. When you pass either of those (the time value or the ISO string) into new Date on the client site, the resulting Date will have the same date/time, but because it's operating in the client's timezone, its local time formatting methods like toString, getFullYear, etc., will use the local timezone of the client.
E.g., change toString to (for instance) toISOString in your code, and on the client:
const dt = new Date(theStringFromTheServer);
console.log(dt.toString()); // Will use the client's timezone to show the date/time

Preserve Local DateTime in Javascript

My customer's store is in GMT +5:30 timezone but the user's locale is in GMT +8 timezone.
Currently, I'm using javascript's .toISOString() function to convert to UTC and storing UTC in the database. I retrieve UTC from the database and send exactly that the browser, so the new Date('2019-11-15T00:00:00Z') function converts the UTC to the browser's locale.
But, if the user opens a record created by GMT +8 timezone user or vice-versa, the dates are getting messed up.
I'm thinking it would be good if I can transfer the exact date the user enters in the browser and send that exact date to the backend to easily offset using the store's timezone?
The frontend is in VueJs and the backend is in C#.
Always store UTC time in database
Just Store the UTC time in your database, In your client-side, Get client's current timezone,
Here, I am getting IANA timezone from client's system
// get client's timezone (From user's system)
var clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
Then, Convert the UTC depends on the timezone and show it to user,
// assume 2019-11-15T00:00:00Z is the UTC date from your database
var convertedTime = new Date('2019-11-15T00:00:00Z').toLocaleString("en-US", {timeZone: clientTimezone});
Example
var clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var timeUtc = '2019-11-15T00:00:00Z';
var convertedTime = new Date(timeUtc).toLocaleString("en-US", {timeZone: clientTimezone});
console.log("Time to Current User : " + convertedTime);
var timeInUsa = new Date(timeUtc).toLocaleString("en-US", {timeZone: "America/New_York"});
console.log("Time in America (New York) : " + timeInUsa);
var timeInAustralia = new Date(timeUtc).toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
console.log("Time in Australia (Brisbane) : " + timeInAustralia);
Note that the js Date object is simply a number that represents an absolute time (independent of any timezone).
So the best encoding/format for transferring and storing a date is that number. IMO this is much simpler than storing a UTC string.
So, on the end-user's machine you would Date.parse the date string provided by the user and this would take account of the user's time zone for you and give you the absolute time number for sending and storing on your backend.
Don't do any formatting or parsing of dates on the backend if you are using Node because there are serious gotcha's and because you shouldn't need to anyway: any client device that needs a date string will do the formatting locally which will automatically convert it to the correct format for their locale and timezone. [edit: the Q did not specify the backend when I wrote this.]
You will need to watch for some gotcha's in the Date.parse function but these are minor compared to the node problems. The most significant IMO is that it will interpret dates in YYYY-MM-DD as ISO 8601 dates (which makes some sense) but then assume that they are GMT if no timezone is specified so you should make sure there is a timezone specified if you use that format.

Get timezone from users browser using moment(timezone).js

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()

How to detect day light saving and convert to BST (local time) in moment js

I am working on a project and suddenly found an issue. Issue was, server is sending Unix timestamps which is GMT but due to daylight saving the date
was populated as GMT. It can be achievable from server end but there is very simple way where we can convert it to local-time zone(in my case GMT to BST)
Create three variables
getPerfectLocalTime
yourUnixTimestamp
yourFormat
And below is the logic, you can use
var GMTtime = moment(yourUnixTimestamp*1000).format('YYYY-MM-DD HH:mm:ss'); // It should be YYYY-MM-DD format
var convertToUtc = moment.utc(GMTtime).format('YYYY-MM-DD HH:mm:ss');
var localTimeToDate = moment.utc(convertToUtc).toDate();
var isDSTDateTime = moment(GMTtime, 'YYYY-MM-DD');
var month = isDSTTime.format('M');
var day = isDSTTime.format('D');
var year = isDSTTime.format('YYYY');
if(moment([year, month, day]).isDST()){
getPerfectLocalTime = moment(localTimeToDate).format(yourFormat);
}else {
getPerfectLocalTime = moment(yourUnixTimestamp*1000).format(yourFormat);
}
Hope it helps anyone in programming world :)
Given that the only input in your example is yourUnixTimestamp, and you are multiplying by 1000, I'll assume that this is a traditional Unix Timestamp - an integer number in terms of whole seconds since midnight 1970-01-01 UTC.
Simply call moment.unix to parse this particular kind of input value. The resulting moment object will already be in local mode, so you can just format it directly.
moment.unix(yourUnixTimestamp).format(yourFormat)
If you want to know whether or not DST is in effect in the local time zone, you can just ask for that directly too.
moment.unix(yourUnixTimestamp).isDST()
But note that you do not need to know this to format the time correctly. Moment already takes this into consideration internally.

Datetime in MST Zone

On ASP.net MVC application where I save the date on datetime field in SQL sever db.It saves like this 2015-04-22 18:43:18.967.So now I need to show it as MST (Mountain Standard Time) on client side.So how can I do that ? I can use Moment.js or any other JavaScript library for that.Thanks in advance.
If you send the timestamp to the client and you are using momentjs, then it's pretty simple
var day = moment(TS_IN_MILLISECONDS).tz('America/Denver')
With the string you provided, you can do this:
var UTCTime = moment.utc('2015-04-22 18:43:18.967').toDate();
var MSTTime = moment(UTCTime).tz('America/Denver').format('YYYY-MM-DD HH:mm:ss');
So this will depend on what local time your server is running in (or if it's just pulling UTC it'll be a bit easier). But you can yank the timezone offset like this: dateTime.getTimezoneOffset(), modify it it to reflect the offset difference between your server's timezone and MST. And then modify your original datetime to reflect the new offset.
This may be a good post for reference.
Also refer to here:
dateTime.setTime( dateTime.getTime() + dateTime.getTimezoneOffset()*[math to adjust your timezone] );

Categories