【问题标题】:Azure Functions (C#): get time zone ids (NodaTime)Azure Functions (C#):获取时区 ID (NodaTime)
【发布时间】:2019-05-27 14:57:33
【问题描述】:
我有一个时间触发的 Azure 函数。 Azure 函数在每次上午 00:00(当地时间)时启动。我想要实现的是在 Azure 函数运行时找到当前为上午 00:00 的时区的时区字符串(例如 Europe/London)。
即,我提供了一个 UTC 值,它为我提供了当前为当地时间上午 00:00 的所有时区 ID。
如何使用 NodaTime 实现这一目标?
【问题讨论】:
标签:
c#
datetime
azure-functions
utc
nodatime
【解决方案1】:
比你的版本稍微简单一点,如果你总是想检查午夜:
static List<string> GetTimeZonesAtMidnight(Instant instant) =>
// Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
DateTimeZoneProviders.Tzdb.GetAllZones()
.Where(zone => instant.InZone(zone).TimeOfDay == LocalTime.Midnight)
.Select(zone => zone.Id)
.ToList();
如果您需要检查非午夜值,请传入LocalTime:
static List<string> GetTimeZonesAtMidnight(Instant instant, LocalTime timeOfDay) =>
// Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
DateTimeZoneProviders.Tzdb.GetAllZones()
.Where(zone => instant.InZone(zone).TimeOfDay == timeOfDay)
.Select(zone => zone.Id)
.ToList();
【解决方案2】:
我的第一种方法(原型)如下所示:
using System;
using System.Collections.Generic;
using NodaTime;
namespace TimeZones
{
class Program
{
static void Main(string[] args)
{
Instant utcDateTime = Instant.FromDateTimeUtc(DateTime.UtcNow);
Console.WriteLine(utcDateTime);
List<string> zoneIds = GetTimeZonesWithCondition(utcDateTime, 0, 0);
Console.ReadLine();
}
static List<string> GetTimeZonesWithCondition(Instant utcDateTime, int hourComparison, int minuteComparison)
{
List<string> zoneIdsCheck = new List<string>();
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
foreach (var id in timeZoneProvider.Ids)
{
var zone = timeZoneProvider[id];
var zoneDateTime = utcDateTime.InZone(zone);
int hourZone = zoneDateTime.Hour;
int minuteZone = zoneDateTime.Minute;
if (hourZone == hourComparison && minuteZone == minuteComparison)
{
zoneIdsCheck.Add(zone.ToString());
Console.WriteLine($"{zone} / {zoneDateTime}");
}
}
return zoneIdsCheck;
}
}
}
如果有人有更好的解决方案,请告诉我。