How to find the client machine time zone using ASP.NET - javascript

I need to find the time zone of the client machine using ASP.NET (C#) or JavaScript. What are the different time zones that are available all over the world and how to convert the date and time based on the users time zone.
Please provide some suggestions or sample coding to change the time based on the time zone.

You cannot find client time zone settings from ASP.NET.
You can use JavaScript to tell the current time, but there are several time zones that can be synchronized at any given time.
In Chrome, you can get the time zone from the JavaScript date object. There's no specific function for it, from what I've found, but the code
(new Date()).toString()
will yield something like
Mon Apr 18 2011 08:58:59 GMT+0200 (W. Europe Daylight Time)
In websites, the best approach I've found has been to have a setting for each user to specify the time zone to display all times in. If the JavaScript getUtcOffset gives a different offset than what is expected for the user's time zone, I'll show a notice for the user to review their settings. If time zone can be guessed from the date (which I've only found to be the case in chrome), I'll suggest that time zone, but I still resort to a select box for the user to manually pick the time zone.
Even so, it is possible to have the wrong time zone setting, without the script noticing it, because for a great part of the year, the two time zones may be perfectly synchronized.
Once you have a time zone (you can enumerate them all with System.TimeZoneInfo.GetSystemTimeZones()), you can convert UTC dates with System.TimeZoneInfo.ConvertTimeFromUtc and System.TimeZoneInfo.ConverTimeToUtc, respectively.

Related

How do I get consistent data across different timezones if I am saving all the dates in UTC +0

I have a system where users from Washington DC can create a post. This post is saved in my system in UTC +0 time. Then, I can use a reporting system which will give me info about every created post in a certain date range. Lets say I select a date range from March 21st 00:00:00 to March 28th 23:59:59 but in my system someone created a post on March 28th 22:30:00 Washington DC time. Washington DC is several hours behind UTC, so this post would be saved at around March 29th 02:30:00, and so when I generate the report for March 21st to March 28th, I will not get the correct result because there is 1 post that has been created on March 28th Washington time, but that is March 29th UTC +0 time.
I first solved this by obtaining the UTC offset of the client and sending it to the server, and so adding that offset to my date range:
// JavaScript
"offsetHours" : parseInt(new Date().getTimezoneOffset() / -60)
"offsetMinutes" : (new Date().getTimezoneOffset() / -60) % 1 * 60
// Python
_range["from"] = strToDate(_range["from"]) - datetime.timedelta(hours = int(request.headers["offsetHours"]), minutes=int(request.headers["offsetMinutes"]))
This solved the issue, but it raised another. Now if I generate a report for the same time range (from 21st to 28th March) from 2 different timezones, I will get different results. This is due to the fact that the 2 users have different offsets and so they affect the from range in different intervals.
Is there any solution to this problem?
You're not necessarily describing a problem, but rather a side effect of how local times around the world work.
At any given time, there is usually more than one "date" in effect somewhere in the world. If you are saving the timestamp of an event that took place, and you have customers around the world, you're not necessarily saving it with the same date that the user thought it was in their own time zone. This is true whether you align the timestamps to UTC or to a specific time zone.
Therefore, you must make a business decision about how your application is intended to work. Do you want your daily reports to reflect posts that were made within a UTC day, or within the day according to the time zone of your business's headquarters? Then store the timestamp in UTC and (optionally) adjust to your business's time zone before or during reporting.
If however you want the daily reports to reflect the date in the user's time zone, then you might want to also store the user's time zone ID (such as America/New_York - not a numeric offset) so that you could convert to that. Keep in mind that if user's are in different time zones, your reports might look strange when examined from a single time zone's perspective.
Another technique that is often used (primarily for performance reasons, but also for clarity of logic), is to keep both a UTC-based timestamp and a separate field for the "business date" that applies. Usually such a field is just a date field, storing a value such as 2021-03-29 without any time or time zone. This field can be pre-converted to a time zone according to whatever rules you decide are applicable for your business. It then becomes a great candidate for an index and works well for range queries for daily reports.
In the end - there is no one "right" way to do it. You have to decide what works best for your use case. If you are working for a larger company and unsure of the business requirements, then ask someone who might already perform a similar activity manually. (Often this is an accounting or sales person in a larger organization.)

How to adjust an array of hours to a preferred timezone?

So a little context, I have an array of 24 arrays -- one for every hour in the day.
So midnight, 0 index, would be [133.00, 234.00] which would indicate 133 actions from 12 - 1230 and 234 actions between 1230 - 1am.
I need to adjust these indexed arrays to account for the user's timezone in a browser with JS, so that if the user is in New York the 0 index (midnight in the user's home turf) is displayed in China's offset (12pm tomorrow, from user's perspective).
I've been trying to think of a solution, I have a simple function for what I've been able to think of
function offsetHourIndex(hourIndex, dataCenterTimeZone) {
let userTime = new Date().setHour(hourIndex)
return moment(userTime).tz(dataCenterTimeZone).hour();
}
How reliable would this approach be?
Your approach has a few problems:
You are assuming that the current date in the local time zone is the correct date for the target time zone. Most of the time, there are two dates active somewhere around the world. For example, 2019-04-02 04:00 in London is 2019-04-01 23:00 in New York. If you just take hour 4 from London but apply it to the current date in New York, you've created a whole new point in time, a day too early.
You assume there will be exactly 24 hours in every day. In time zones that have transitions for daylight saving time or changes in standard time, you may have more or less hours of local time on a the day of the transition.
In the case of a backward transition, there is a period of ambiguous local time. For example, when US Pacific Time moves from PDT to PST in November, the hour from 1:00-1:59 is repeated. If data from both hours are summarized into array element 1, then you will have higher than normal results for that hour. The opposite is true for forward transitions - you will have an hour with no data.
The time zone setting of the server can be a fickle thing. What if you change data centers? What if you move to the cloud? What if you are operating multiple data centers? What if a server administrator thinks all they are affecting by changing the system time zone is the readout on the taskbar or front panel, etc., and then it affects your application? In general one should avoid these things by never relying on the server's local time zone setting.
You can avoid all of these problems by basing everything on Coordinated Universal Time (UTC) - especially the array. Then you can be ignorant of any server time zone setting, and just base everything off the current UTC day, which is the same all over the world.
This will give you the local hour from the given UTC hour in your index:
var localHour = moment.utc({hour: hourIndex}).local().hour();
You do not need moment-timezone for the above recommendation.
However, if you really feel like you need to convert from a specific time zone to the browser local time, then you would use moment-timezone like this:
var localHour = moment.tz({hour: hourIndex}, timeZoneName).local().hour();
Note when you do this, you also have another problem - not every time zone is offset by a whole number of hours. For example, India uses UTC+05:30. There are many that are :30 and a few that are :45. By tracking hours only, you're not providing enough information to properly convert to the correct local hour. Your results may be off by one.
It seems reasonable. And the code should work as long as you have the properly formatted inputs. I like the brevity and clarity of the function. Any reason you are concerned about reliability?
You might mention in your question that you are using the moment and moment-timezone packages here to derive your data via its functions (moment & tz) on this line of code:
return moment(userTime).tz(dataCenterTimeZone).hour();
Your function may appear a bit cryptic without the imports in your example for folks reading here to understand, such as :
import * as moment from 'moment';
import 'moment-timezone';

Display date in timezone that is not the user's local timezone

I've tried searching for this but it's a pretty specific question. I have a React application where users will be looking at a calendar that can be switch between multiple timezones. I'm using Moment with it's Timezone plugin to try and standardize these times as much as possible.
There is a use case with this application where, for example, a user may be in the US/Eastern (UTC -05:00) timezone viewing a calendar that is set in the US/Mountain (UTC -07:00) timezone.
Right now, I'm keeping my dates in UTC to try and minimize the confusion, however I will need this user, in the Eastern timezone, to be able to see the date in the Mountain timezone. For instance, clicking on a calendar appointment, which is set in Mountain time, will display at 3pm MT. However, right now, when I take the UTC date, it's being converted into the user's local time. A 3pm MT appointment is displaying as 5pm ET.
// I'd like it to display 2017-12-20T15:00:00-07.00 to the end user
moment('2017-12-20T22:00:00Z').format() // returns 2017-12-20T17:00:00-05.00
My question is, using the calendar offset (UTC -07:00), how can I display that time in MT as opposed to the user's local time using Moment and Moment Timezone? I don't have access to any other timezone information, besides the offset. I'm tried going through Moment Timezone's docs but it seems I need a name to create the time in a timezone different from the user's local timezone.
To use moment-timezone, you will need moment#2.9.0+, moment-timezone.js, and the moment-timezone data.
I think this will helps you.
https://momentjs.com/timezone/docs/

TimeZone vs Offset to store user timezone

I realize this is a commonly asked question but I couldn't find any posts that point out the disadvantages of using/storing offset for user's time zone. Is this not a better and more efficient way?
Long drop down lists of time zones are not user friendly and most of such lists don't have all the cities anyway. They also require user to specify their time zone. I feel it may be much better to simply detect it. In my case, my app is an ASP.NET Core app with Reach front end and it's pretty easy to capture user's time zone offset via JavaScript.
Any reason why storing the offset of user's timezone is NOT a good idea?
Any reason why storing the offset of user's timezone is NOT a good idea?
Yes. Many. A time zone and an offset are not the same thing. A time zone represents a geographical area in which local time is aligned. A time zone may undergo several different changes in its offset from UTC. Some of which are regular (like daylight saving time), and some of which are irregular (like when a government changes its standard time or dst rules).
... In my case, I simply want to display all date time values in user’s current time zone so that they’re meaningful to the user.
Ok, so let's say you check the user's current time zone offset and it is UTC-7. So you apply that to some dates and times in your application and done - so you think. Except that you didn't take into account that the user is in California, and one of your dates is in December when the offset should be UTC-8.
So you try to correct for that, and work out the rules of "when I see -7, it might be -8 sometimes". Except now you have a user come along who is in Colorado, where it is -7 during the winter and -6 during the summer. Or another user from Arizona, where most of the state is in -7 for the whole year. How do you know which set of rules to follow? Without referencing an actual time zone, it cannot be done.
This gets even more complex worldwide. For example, the number of variations for UTC+2 is just crazy. Even for countries that switch between UTC+2 and UTC+3 - they don't all switch on the same dates or at the same time of day!
See also: The Problem with Time & Timezones - Computerphile (YouTube)
and the StackOverflow timezone tag wiki.

How to convert timespan using offset

I have MVC web application. I am storing UTC time in database. (Not datetime but just a time). In C# When I retrieve this time from the database I get timespan object back. I also have offset available in minutes. For example.
double offset = 600;
How do I use this offset to convert timespan to local datetime.
Note I don't want to use DateTime.ToLocalTime () method because that will use server's timezone.
UPDATE1
I am using the Javascript new Date().getTimezoneOffset() method to get the client's offset, and i have offset value stored on the server. Then I also have drop down list that show times as 12:00 AM, 12.30 AM, 1:00 AM etc etc. The dropdownlist is bound to model property SelectedDateTime of type DateTime. Idea is to convert user selected time to UTC and then UTC to localtime based on the offset. So lets say i have offset 300 minitues that would be 300/60 = 5 hours
double offset = 5.00; // this is available on the server
When the user selects time in a drop down list, I am getting a datetime object on the server, ignoring the date part i want to store UTC time into database. This is how I'm converting to UTC time.
TimeSpan utcTime = SelectedDateTime.AddHours(offset).TimeOfday;
I store this utcTime into the database. Now I want to convert UTC timespan into the client's datetime.
I am assuming i have Subtract offset now
var newLocalTimeSpan = utcTime.Subtract(TimeSpan.FromHours(offset));
var newLocalDateTime = new DateTime(newLocalTimeSpan.Ticks, DateTimeKind.Local);
However this throws the error:
Ticks must be between DateTime.MinValue.Ticks and
DateTime.MaxValue.Ticks.\r\nParameter name: ticks
For example with offest 5 hours, If user selects 8:00 PM then it will be converted to UTC and will be stored as 01:00:00.0000000 in database. When I retrieve the UTC value from database its '1:00:00 AM'. Then I subtract 5 hours form this TimeSpan which equals to `-4' now and if I pass Ticks to DateTime..i get above error.
NOTES: If you are curious why model property is DateTime instead of TimeSpan thats because i am using Kendo TimePicker which needs DateTime type.
UPDATE 2
I really appreciate all for your help. I have gone through all the articles #Matt Johnson has posted and it looks like I should not be using offset for calculating the UTC time. Mainly because of the day light time saving. But instead I should be using timezone. So I have 3 options here to find client’s time zone:
1> Use JavaScript to detect time zone
In JavaScript I can do new Date().toString() which returns date time as Sun May 22 2016 02:12:36 GMT-0500 (Central Daylight Time) I can then parse the string to get “Central Daylight Time” and post it to the server. However on server, for .net “Central Daylight Time” is not a valid windows time zone ID.
Question
Is this correct approach? Is JavaScript returning IANA zone id? Will it always return IANA zone id?
If JavaScript is returning IANA Id then I can use Matt’s article here to get windows time zone id
2> Use http://momentjs.com/ to detect client’s time zone
Question
Is momentjs returns IANA zone id?
If momentjs return IANA zone id then I can use Matt’s article above to get windows zone id. One of the reason I don’t like this approach is because I have to use 2 third party libraries momentjs and Noda Time
3> Provide user a drop down list using TimeZoneInfo.GetSystemTimeZones() and let the user selects the timezone.
User will select a time and timezone, then on server I will convert it to UTC using selected timezone and save it DB. However I have to show that time on some other pages, So I again need timezone. That means I have to put the drop down list in such a place on UI where it will be available all the time. Like top menu.
(I can certainly save timezone into DB along with the time, however if user travel to other place he will still see time in initially selected time zone. Which I don’t want)
Are these correct approaches? Am i missing something?
Question
Assume that I implement timezone selection using one of the approach above and i have correct client's time zone with windows timezone id on server in some variable.
Now lets say user selects 6:00 PM (Central Daylight Time , UTC -5) which will convert to UTC as 23:00:00. As long we are in Central Daylight Time the conversion from UTC to local will show 6:00 PM. Once we go into Central Standard Time which is UTC -6 Will the conversion still show 6:00 PM or 5:00 PM?
I am planning to use TimeZoneInfo.ConvertFromUtc(datetimevalue, timezone) method for converting UTC to Local
In general, there are only two viable approaches:
Pass only UTC dates and times to the client, and do all conversions to local time in the browser using JavaScript.
Use this approach when you don't care what the time zone actually is, but you just want it to match the browser's local time.
The Date object can do this, but you may find it easier to use a library such as moment.js, which gives you better control of output format, among other things.
Apply a time zone (not just an offset) to the UTC date and time on the server side, to produce the correct local time value.
Use this approach when the time zone affects an entire application, and needs to be known in server-side business logic.
You can try to guess the user's time zone using jsTimeZoneDetect or moment.tz.guess() in moment-timezone. However, it's just a guess, and it is always an IANA time zone ID (such as America/Los_Angeles).
Asking the user for their time zone from a list is a good idea. Usually one would place this on a user settings or profile page. You can use the guess made earlier to pick a default value from the list.
You will indeed need to use Noda Time on the server if you are using IANA time zones on the client.
Some applications choose to list Windows time zones instead, which is a much simpler approach as you can get everything from the TimeZoneInfo class. However, recognize that there are limitations with this approach including:
Localization issues, as you cannot easily get at display name strings other than the ones matching the operating system's default language, not .NET's globalization and localization features.
Maintainability issues, as you yield control to the operating system for keeping the time zone data updated. This may seem more convenient, but you may find that your hands are tied when keeping up with short-notice time zone changes. This is especially problematic when you don't have control over how or when updates are applied to the OS, such as with Microsoft Azure App Service.
Compatibility issues, as Windows time zones aren't generally recognized outside of Windows. If you ever expose the user's time zone setting in an API, you'll likely have translation issues for callers from other platforms.
Now, getting to your specific points:
I am using javascript new Date().getTimezoneOffset() method to get the client's offset...
That gives you the client's current offset. You have no guarantees that it is the correct time zone to apply for an arbitrary date and time.
If wanted to apply a fixed offset to a UTC DateTime in C#, the best way is with a DateTimeOffset.
DateTime utc = new DateTime(2016, 12, 31, 0, 0, 0, DateTimeKind.Utc);
DateTimeOffset dto = new DateTimeOffset(utc); // DateTimeKind matters here
TimeSpan offset = TimeSpan.FromMinutes(-300); // The offset is inverse of JavaScript's
DateTimeOffset result = dto.ToOffset(offset);
But do note this is only for a fixed time zone offset. For a true time zone, you would use the TimeZoneInfo class if you're using Windows time zones, or you would use NodaTime's DateTimeZone class for IANA time zones.
In JavaScript I can do new Date().toString() which returns date time as Sun May 22 2016 02:12:36 GMT-0500 (Central Daylight Time) I can then parse the string to get "Central Daylight Time" and post it to the server.
No, this approach is not recommended, for several reasons:
There's no guarantee you will get output in any particular format from JavaScript's toString function. The results are implementation specific, and will vary across browsers and platforms.
They are generally intended for display purposes. When DST is in effect, they'll show a daylight name, and when standard time is in effect they'll show a standard name.
They are often localized for the user's language, English, French, Chinese, etc.
The only native API that can return the user's time zone is:
Intl.DateTimeFormat().resolvedOptions().timeZone
This is part of the ECMAScript Internationalization API. Unfortunately, it currently only works in a handful of browsers. Both jsTimeZoneDetect and moment.tz.guess() will use this API if it's available, then will fall back to their own guessing logic if not.
Assume that i implement timezone selection using one of the approach above and i have correct client's time zone with windows timezone id on server in some variable. Now lets say user selects 6:00 PM (Central Daylight Time , UTC -5) which will convert to UTC as 23:00:00. As long we are in Central Daylight Time the conversion from UTC to local will show 6:00 PM. Once we go into Central Standard Time which is UTC -6 Will the conversion still show 6:00 PM or 5:00 PM?
I am planning to use TimeZoneInfo.ConvertFromUtc(datetimevalue, timezone) method for converting UTC to Local
As you said earlier, "Central Daylight Time" is not a valid Windows time zone identifier. Your user wouldn't pick that. You'd display a list generated from TimeZoneInfo.GetSystemTimeZones(), showing the DisplayName to the user, and using the Id for the value. The Id would be "Central Standard Time", which indeed is the correct identifier for US Central Time, inclusive of both CST and CDT - despite having the word "Standard" in the string.
You need to convert the TimeSpan to a DateTime, using the current Year, Month and Day. If you subtract from a TimeSpan without doing so, it can result in an unobtainable date.
Also, I noticed in your update that you left the results in a DateTime, so I did the same.
This code is showing you the time if the UTC time was 1:00 AM, as your problem states.
double offset = 5.00;
TimeSpan utcTime = new TimeSpan(1,0,0); //setting manually to your representation of 1 am.
DateTime newLocalDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, utcTime.Hours, utcTime.Minutes, utcTime.Seconds);
newLocalDateTime = newLocalDateTime.Subtract(TimeSpan.FromHours(offset));

Categories