C# 正在分析用户输入,包括tz数据库时区名称
我正试图用Noda Time解析用户输入 输入:C# 正在分析用户输入,包括tz数据库时区名称,c#,timezone,nodatime,C#,Timezone,Nodatime,我正试图用Noda Time解析用户输入 输入: 日期格式为YYYY-MM-DD 时辰 分钟 tz数据库时区名称(从Google的时区API返回) 我需要将此数据转换为UTC和其他时区,也基于tz数据库时区名称 目前,我正试图弄清楚LocalDateTime和ZonedDateTime之间的区别,但也许有人能在我(希望)弄明白这一点之前演示如何做到这一点。提供了大量信息,虽然有些过时,但在官方文档中很容易找到相关的方法名称 下面是一些演示代码 string date = "2013-01-2
- 日期格式为
YYYY-MM-DD
- 时辰
- 分钟
- tz数据库时区名称(从Google的时区API返回)
LocalDateTime
和ZonedDateTime
之间的区别,但也许有人能在我(希望)弄明白这一点之前演示如何做到这一点。提供了大量信息,虽然有些过时,但在官方文档中很容易找到相关的方法名称
下面是一些演示代码
string date = "2013-01-22";
string hour = "13";
string minute = "15";
var result = LocalDateTimePattern.ExtendedIsoPattern.Parse(date + "T" + hour + ":" + minute + ":00");
if (result.Success == true)
{
DateTimeZone source_zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/Brussels");
DateTimeZone target_zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Australia/Melbourne");
if (source_zone != null && target_zone != null)
{
ZonedDateTime source_zoned_dt = result.Value.InZoneStrictly(source_zone);
Console.WriteLine(source_zoned_dt.ToInstant());
Console.WriteLine(source_zoned_dt);
Console.WriteLine(source_zoned_dt.WithZone(target_zone));
}
else
{
Console.WriteLine("time zone not found");
}
}
else
{
Console.WriteLine("parsing failed");
}
您的答案与我的答案非常接近,但如果您将日期、小时和分钟用不同的字符串表示,我会使用:
var zoneProvider = DateTimeZoneProviders.Tzdb;
var sourceZone = zoneProvider.GetZoneOrNull("Europe/Brussels");
var targetZone = zoneProvider.GetZoneOrNull("Australia/Melbourne");
if (sourceZone == null || targetZone == null)
{
Console.WriteLine("Time zone not found");
return;
}
var dateParseResult = LocalDatePattern.IsoPattern.Parse(date);
int hourValue, minuteValue;
if (!dateParseResult.Success ||
!int.TryParse(hour, out hourValue) ||
!int.TryParse(minute, out minuteValue))
{
Console.WriteLine("Parsing failed");
return;
}
var localDateTime = dateParseResult.Value + new LocalTime(hour, minute);
var zonedDateTime = localDateTime.InZoneStrictly(sourceZone);
Console.WriteLine(zonedDateTime.ToInstant());
Console.WriteLine(zonedDateTime);
Console.WriteLine(zonedDateTime.WithZone(targetZone));
这里唯一显著的区别是解析——我不会把所有的位粘在一起;我只需要分别解析字符串。(对于失败,我也更喜欢“提前退出”:
不过,您应该注意区域中
的含义-如果输入的本地日期/时间不明确,您肯定想失败吗?谢谢您的见解。我们仍然需要决定如何处理不明确的值,所以我只是在测试程序中直接使用了inzone
。@Stijn:只要您知道可能的问题和可用的选项,我很高兴:)