Reputation: 2666
This seems like a simple problem, but looks to be harder than it seems:
How do I convert Midnight of a specified timezone and convert it to Utc time (regardless of the timezone of the local computer)?
One example: Today Midnight CET is 11pm (the date before) in UTC.
I tried the following:
DateTime midnight = TimeZoneInfo.ConvertTime(DateTime.UtcNow, specifiedTimeZoneInfo).Date;
DateTime utcTime = midnight.ToUniversalTime();
The problem is that this code only works if the timezone of the local computer running the code is the same timezone as used in the TimeZoneInfo.ConvertTime.
How can one do this regardless of the timezone of the local computer?
Upvotes: 4
Views: 1344
Reputation: 125207
Consider the following code:
var cestZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var cestNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cestZone);
var cestMidnight = cestNow.Date;
var cestMidnightInUTC = TimeZoneInfo.ConvertTimeToUtc(cestMidnight, cestZone);
When DateTime.UtcNow
is 12/29/2018 - 11:30:00 PM
Will result in:
If you live in CEST and look at clock
cestNow: 12/30/2018 - 12:30:00 AM
If you live in CEST and had a look at clock at midnight (start of today, 30 minutes ago)
cestMidnight: 12/30/2018 - 12:00:00 AM
At your midnight, UTC was
cestMidnightInUTC: 12/29/2018 - 11:00:00 PM
Note: 12:00:00 AM
is start of the day. So for example if utc now is 12/29/2018 - 11:30:00 PM
, midnight was 23:30
hours ago at 12/29/2018 - 12:00:00 AM
utc.
Upvotes: 5