我要求管理员选择一些 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
所以,我想到了获取他们的时区并根据 Server Time
进行计算.
例如:我的服务器位于Canada
.So,我想到了计算Time to Alert
在 India
基于 India TimeZone
和 save the Time in Db
.所以我的windows服务将在那个印度时间运行并推送警报。
但是为此,我需要在数据库中保存多条不同时间的记录。
所以,为了获得 TimeZone
基于国家代码,我使用了 NodaTime
var CountryInfo = (from location in TzdbDateTimeZoneSource.Default.ZoneLocations
where location.CountryCode.Equals(CountryCode,
StringComparison.OrdinalIgnoreCase)
select new { location.ZoneId, location.CountryName })
.FirstOrDefault();
我得到了 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.
}
请记住,这是假设一个国家/地区只有一个时区 - 情况并非总是如此。想想美国,那里有很多 时区...
关于c# - NodaTime 根据国家代码获取国家时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905239/