我遇到了如何确定是否DateTime.UtcNow
(例如 2018-01-01T20:00:00Z)属于另一个时区的给定日期和时间范围内。没有给出具体日期,只是一周中的几天和一天中的时间。给定时间采用 ISO 8601 标准格式。
为了简化这个问题,可以是如何检查UTC时间是否在中国的工作时间内。
例如,给定的日期和时间范围是由中国人给出的时区+08:00,它可以是:FromDayOfWeek = "Friday", FromTimeOfDay = "17:00:00+8:00", ToDayOfWeek = "Monday", ToTimeOfWeek = "08:00:00+8:00".
我需要确定中国的“现在”是否在给定范围(星期五 17:00:00+8:00 - 星期一 08:00:00+8:00)之间的某个时间。
我陷入了如何转换 DateTime 并获取当地时间的星期几的问题,因为 2018-01-01T20:00:00Z 在英国是星期一,但同时,因为中国是 +08:00 ,在中国已经是星期二了。
我的做法:
// parse the time to get the zone first (+08:00)
TimeSpan ts = TimeSpan.Parse("-08:00");
// Create a custom time zone since the time zone id is not given, and cannot be searched by SearchTimeZoneById
TimeZoneInfo tzi = TimeZoneInfo.CreateCustomTimeZone(zoneId, ts, displayName, standardName);
DateTime localDateTime = TimeZoneInfo.ConvertTime(Date.UtcNow, tzi);
String localDay = localDateTime.DayOfWeek;
// Determine if localDay is between FromDayOfWeek and ToDayOfWeek
// cast the days to integers from 1 (Monday) to 7 (Sunday)
// create an array of days in integar days = [5, 6, 7, 1]
// if days.contains(localDays), check the times
...
谁能提出一些更好的解决方案?我不确定我的是否有效,并且在如何处理夏令时(因为区域会改变)以及如何检查时间范围方面存在漏洞。我是 C# 新手,任何我可以使用的库的建议都很棒!