First let me set up the senario:
Datetime is always stored in the database in EST. I have a need to convert it to the client timezone or from the client timezone to the server timezone.
The client timezone is known at the time of request. So, after reading/googling it, I don't feel the solution that I came with is adequate or maybe I feel it is bit hackish.
The code is the following:
public static class TimeZoneUtility
{
static readonly TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
public static DateTime ConvertToServerDateTime(DateTime clientTime, TimeZoneInfo clientTimeZone)
{
clientTime = DateTime.SpecifyKind(clientTime, DateTimeKind.Unspecified);
DateTimeOffset clientDateTimeOffset = new DateTimeOffset(clientTime, clientTimeZone.GetUtcOffset(clientTime));
DateTimeOffset serverDateTimeOffset = TimeZoneInfo.ConvertTime(clientDateTimeOffset, serverTimeZone);
return serverDateTimeOffset.DateTime;
}
public static DateTime ConvertToClientDateTime(DateTime serverTime, TimeZoneInfo clientTimeZone)
{
DateTimeOffset serverTimeOffset = new DateTimeOffset(serverTime, serverTimeZone.GetUtcOffset(serverTime));
DateTimeOffset client = TimeZoneInfo.ConvertTime(serverTimeOffset, clientTimeZone);
return client.DateTime;
}
}
I have read the following answer and i modeled the solution after it. (Having problems with converting my DateTime to UTC)
Does anyone see a problem with the solution below? Please note I had to recreate the clienttime intentionally with DateTime.SpecifyKind(clientTime, DateTimeKind.Unspecified)
becasue the kind was Local and It was throwing an exception.
If you see a problem, please explain it and suggest a workaround.
Thanks,