这看起来是一个简单的问题,但看起来比看起来更难:
如何将指定时区的午夜转换为UTC时间(与本地计算机的时区无关)?
举个例子:今天午夜 CET 是 UTC 时间晚上 11 点(前一天)。
我尝试了以下方法:
DateTime midnight = TimeZoneInfo.ConvertTime(DateTime.UtcNow, specifiedTimeZoneInfo).Date;
DateTime utcTime = midnight.ToUniversalTime();
Run Code Online (Sandbox Code Playgroud)
问题是,仅当运行代码的本地计算机的时区与 TimeZoneInfo.ConvertTime 中使用的时区相同时,此代码才有效。
无论本地计算机的时区如何,如何才能做到这一点?
考虑以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
什么时候DateTime.UtcNow将12/29/2018 - 11:30:00 PM导致:
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
Run Code Online (Sandbox Code Playgroud)
注:12:00:00 AM是一天的开始。例如,如果 UTC 现在是12/29/2018 - 11:30:00 PM,则午夜是23:30几小时前的12/29/2018 - 12:00:00 AMUTC。