Our application was designed to handle user from different Geographic location.
We are unable to detect what is the current end user local time and
I'm a little confused by the phrasing of your question, but it appears that you would like to determine the time zone of your user.
Have you tried asking them? Many applications have the user pick their time zone in user settings.
You could pick from a drop-down list, or a pair of lists (country, then time zone within the country), or from a map-based time zone picker control.
You could take a guess and use that as the default unless your user changes it.
If you go down that route, you will need to be able to use IANA/Olson time zones, which is where Noda Time comes into play. You can access them from DateTimeZoneProviders.Tzdb
.
The hosting location is irrelevant if you are using UTC. That's a good thing.
Also, if you're using Noda Time, then you probably should use SystemClock.Instance.Now
instead of DateTime.UtcNow
.
See also here and here.
Also - an alternative solution would be just to pass the UTC time to the browser and load it into a JavaScript Date
object. The browser can convert that to the user's local time. You could also use a library like moment.js to make this easier.
Regarding your approach of mapping culture codes to time zones:
That will not work, for several reasons:
Many people use a different culture setting on their computer than the area that they are physically in. For example, I might be an a US-English speaker living in Germany, my culture code is likely still en-US
, not de-DE
.
A culture code containing a country is used to distinguish between dialects of a language. When you see es-MX
, that means "Spanish, as spoken in Mexico". It does not mean that the user is actually in Mexico. It just means that user speaks that dialect of Spanish, as compared to es-ES
which means "Spanish, as spoken in Spain".
Even if the country portion of the culture code could be reliable, there are many countries that have multiple time zones! For example, what would you put in your mapping list for en-US
? You can't just assume that we are all on Eastern Standard Time.
Now, I've explained why your current approach won't work, I strongly suggest you take my original advice. Very simply:
Determine the time zone of the user, preferably by asking them, perhaps with some assistance by one of the utilities I linked to above.
You're storing UTC, so just convert to that time zone for display.
Using Microsoft Time ZonesTimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
DateTime localDatetime = TimeZoneInfo.ConvertTimeFromUtc(yourUTCDateTime, tz);
Using IANA Time Zones and Noda Time
DateTimeZone tz = DateTimeZoneProviders.Tzdb["Europe/Stockholm"];
Instant theInstant = Instant.FromDateTimeUtc(yourUTCDateTime);
LocalDateTime localDateTime = theInstant.InZone(tz);