Rea*_*eel 1 c# asp.net datetime utc nodatime
我有一个要求,管理员将为该国家/地区列表选择一些用户countries List和Time for Alert用户.
让我们说管理员24/07/2014 09:00 AM在国家/地区中选择India,Malaysia and Canada,他们需要根据这些警报获取警报,their TimeZone并且每个国家/地区的用户都需要获取警报User's Local 9 AM Time.
所以,我只有他们country Codes喜欢IN,MY,CA
所以,我想到了他们的TimeZones和基于的计算Server Time.
例如:我的网站服务器位于Canada.所以,我认为心计Time to Alert的India基础上,India TimeZone和save the Time in Db.所以我的窗口服务将在印度时间运行,推动警报.
但为此,我需要在Db中以不同的时间保存多个记录.
因此,为了获得TimeZone基于CountryCode的内容,我使用了NodaTime
var CountryInfo = (from location in TzdbDateTimeZoneSource.Default.ZoneLocations
where location.CountryCode.Equals(CountryCode,
StringComparison.OrdinalIgnoreCase)
select new { location.ZoneId, location.CountryName })
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
我TimeZoneID从这个查询得到了.
我们可以得到CurrentDate and Time的CountryCode基础上Admin's Selected DateTime?
你的代码几乎是正确的 - 虽然它可以稍微简化,并且更易于测试,它应该处理没有这样的区域的情况......
// You should use dependency injection really - that makes the code much more
// testable. Basically, you want an IClock...
IClock clock = SystemClock.Instance;
var countryCode = "IN";
var location = TzdbDateTimeZoneSource.Default.ZoneLocations
.FirstOrDefault(l => l.CountryCode == countryCode);
if (location == null)
{
// This is up to you - there's no location with your desired country code.
}
else
{
var zone = DateTimeZoneProviders.Tzdb[location.ZoneId];
var zonedNow = clock.Now.InZone(zone);
// Now do what you want with zonedNow... I'd avoid going back into BCL
// types, myself.
}
Run Code Online (Sandbox Code Playgroud)
请记住,这假设一个国家只有一个时区 - 情况并非总是如此.想想美国,那里有很多时区......