Show UTC time according to custom time zone
I have some date and time values coming from SharePoint. SharePoint stores all time in UTC format. Thus, when displayed to the user, I convert UTC time to local timezone using this code -
internal static DateTime? ConvertTimeFromUtc(DateTime? utcTime)
{
if (utcTime.HasValue)
{
return TimeZoneInfo.ConvertTimeFromUtc(utcTime.Value, TimeZoneInfo.Local);
}
return null;
}
Am I correct in saying that this will return the time according to the timezone of the server that hosts the web application?
Our production server is currently located in the UK and users are also located in the UK. So the above code will work fine.
But in the future, the production server and even users may be anywhere in the world. What should I do to make it error-free for future improvement?
Do I need to use javascript to find the user's current timezone, store this information in the session, and then use that information when showing any datetime value?
Thank!
source to share
The class TimeZoneInfo
can be used to manage your time zones.
Assuming that you can, on the client side, get a string that matches the values Id
used TimeZoneInfo
(which, in turn, are straight from the Windows registry, but are designed to match the standardized English names for timezones) then you can use TimeZoneInfo.FindSystemTimeZoneById
to find the correct object and use, for example , ConvertTimeFromUtc
to convert a local time for display.
I haven't used it, but there is also a Noda Time library to handle all your date and time management needs. A similar JavaScript library , Moment.js , which can be useful if (as it seems) you have a JavaScript client and want to handle local times in the client code.
I am not familiar with JavaScript, but I am assuming it has built-in support for timezones, and of course there is at least one library for that.
If it were me, I would try to handle all local time zones on the client side. That is, your server side code shouldn't care about the local timezone. At best, if you want the user to be able to override the local timezone on their workstation, you can save this setting and pass it to the client later. But the client code must do the conversion to local time (or whatever the user has chosen as their "local" time zone).
source to share