Reputation: 734
I want to convert any dateTime value to UTC. We have a method that takes a dateTime parameter as an input. We assume that value as EST always. But, then not sure if the kind property will be UTC, EST or unspecified. Also, timeZone can be anything. But, irrespective of its kind and timezone info, we know the value that will be passed to that method is EST and want to convert to UTC. What would be the best way?
var estTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var newEstDateTimeValue = TimeZoneInfo.ConvertTimeToUtc(estTime, estTimeZone);
I tried above but it throws argument exception because the kind property is utc and I assume sourceTimeZone does not equal Utc and hence as per MSDN website argument exception is expected. But we would like to convert any dateTime value without looking at kind or sourceTimeZone to UTC. Any recommendations would be highly appreciated. Thanks in advance,
Upvotes: 2
Views: 1924
Reputation: 2624
When time zones are important to your .NET application, I always recommend the usage of DateTimeOffset instead of DateTime. In most cases you can swap out your use of DateTime easily with DateTimeOffset and not break your code. DateTimeOffset has a method ToUniversalTime() which will give you UTC.
I would also suggest reading this article to understand the difference between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo:
https://learn.microsoft.com/en-us/dotnet/standard/datetime/choosing-between-datetime
Upvotes: 4