How can I get time zone information from Utc date time object and timezone offset value

Viewed 136

Given a UTC date time (see the utc variable below) and a timezone Offset value (see the timezoneOffsetMilliSeconds variable below), how do can I get time zone information of the original user date time input?

Details of what I am doing and want to do more:

var originalUserInput = DateTime.Now; // got from user input as original input.

decimal timezoneOffsetMilliSeconds = 18000000; // Example: "Central Standard Time" time zone off set. Got from user input.

var utc = originalUserInput .AddMilliseconds((double)timezoneOffsetMilliSeconds); // convert to UTC date time to store into database.

var backToUserInput = utc.AddMilliseconds((double)-timezoneOffsetMilliSeconds);  // got from database for UTC date time and convert it back to original user input

My question: how can get user's time zone information (e.g. "Central Standard Time", "CST", or the like ) from database-stored utc and stored timezoneOffsetMilliSeconds values?

Thank you

1 Answers

If this is a local application and not a web application you can do something like this.

Option 1: Store the Offset

var currentLocalTime = DateTime.Now; // or whatever user time input is

var currentUTCTime = currentLocalTime.ToUniversalTime(); // store utc time in db
var utcOffset = (currentLocalTime - currentUTCTime).Hours; //store utc offset in db

var utcTimeFormattedToLocalTime = currentUTCTime.AddHours(utcOffset); //recalculate the local time from db fields

Output is as follows:

Local Time: 8/6/2022 3:36:46 PM
UTC Time: 8/6/2022 8:36:46 PM
Offset: -5
Recalculated Local Time From UTC with Offset: 8/6/2022 3:36:46 PM

Option 2: Convert UTC To Local Time based on Machine where code is running

var userInputDate = DateTime.Now; //or whatever the user inputs
var utcDate = userInputDate.ToUniversalTime(); //save to DB

var localTime = utcDate.ToLocalTime(); // this will convert to users local time based on their machines timezones, or wherever the code is ran.

Output:

Local Time: 8/6/2022 3:37:44 PM
UTC Time: 8/6/2022 8:37:44 PM

Option 3:

Get offset and then use that to calculate based on local machine, or where code is running.

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

You can use offset above on your DB stored UTC value and not have to store the offset if you don't want to.

If this is a web application you will need to do things differently, but you did not specify in your OP. So comment if that is the case.

If you are wanting the users Timezone info you can use the TimeZoneInfo class.

You can do something like this:

var tz = TimeZoneInfo.Local;

This will return you this:

enter image description here

From you can you dot off on your variable 'tz' to get Standard time.

tz.StandardName = Central Standard Time

Related