Reputation: 4895
I want to initialize DateTime in Eastern Standard Time and then convert to universal time.
I have One DateTime (CurrentDT) whose TimeZone is not set, but it is in EST. it is parsedExact from following sting
"ddd, d MMM yyyy H:mm:ss"
I have written following code to solve the problem.
TimeZoneInfo currentTimeZone=null;
currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
CurrentDT=TimeZoneInfo.ConvertTime(CurrentDT, currentTimeZone);
CurrentDT = CurrentDT.ToUniversalTime();
The Problem is that it looks like i am doing wrong. I am converting DateTime,which is in local time zone to Eastern Standerd Time and then to universal standard Time. I don't know how can i initialize TimeZone of CurrentDt initially. Kindly help me understand Thankyou.
Upvotes: 4
Views: 1830
Reputation: 8207
In some cases you could use (relatively) new type DateTimeOffset
, like here:
var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var offset = est.GetUtcOffset();
var dataTimeOffset = new DateTimeOffset(dateTimeWithoutOffset, offset);
var result = dateTimeOffset.UtcDateTime;
Since you should work in different time zones, DateTimeOffset
can make your code more clear.
Upvotes: 1
Reputation: 4017
If I remember well, DateTime
doesn't preserve info about TimeZone
, but if you know that a certain DateTime
is in a specific TimeZone
you can get the UTC from it doing something like this:
var UtcDateTime = TimeZoneInfo.ConvertTimeToUtc(CurrentDt, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")); // 1st param is the date to convert and the second is its TimeZone
Upvotes: 2