c# - NodaTime 根据国家代码获取国家时间

标签 c# asp.net datetime utc nodatime

我要求管理员选择一些 countries ListTime for Alert对于该国家/地区列表的用户。

假设管理员选择 24/07/2014 09:00 AM在国家India,Malaysia and Canada , 他们需要根据 their TimeZone 获取警报每个国家/地区的用户都需要在 User's Local 9 AM Time 获得警报.

所以,我只有他们的country CodesIN,MY,CA

所以,我想到了获取他们的时区并根据 Server Time 进行计算.

例如:我的服务器位于Canada .So,我想到了计算Time to AlertIndia基于 India TimeZonesave 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/

相关文章:

c# - 从 C# 启动 Java 平台

c# - 如何避免方法在链中相互调用?

javascript - jquery 在 asp.net 中不起作用

c# - 控件没有出现在 CodeBehind 中?

python - 使用Postgresql使Sqlalchemy在过滤器中使用日期

python - 如何将日期时间字符串转换回日期时间对象?

c# - 如何在新创建的 .NET Core 2.0 Web 应用程序中以 .NET Standard 2.0 为目标?

c# - LibreOffice 5 Bootstrap.bootstrap 抛出错误代码为 -2147467259 的 ExternalException

c# - 从 Windows 身份验证中获取 `ICredentials`

php - 如何在 php 中强制更改日期时间中的日期