You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NodaTime的ZonedDateTimePattern解析ZonedDateTime字符串失败问题

问题根因

你使用的ZonedDateTimePattern.GeneralFormatOnlyIso属于仅格式化专用的模式实例,设计上未实现解析逻辑,因此即便是它自身输出的格式化字符串,也无法通过同一个实例完成反向解析。

解决方案

你需要自行构造同时支持格式化、解析双向操作的ZonedDateTimePattern实例,构造时必须明确指定时区提供者,保证解析过程可以匹配到对应的时区ID。

修改后的可运行代码如下:

Instant thisNow = SystemClock.Instance.GetCurrentInstant();
var timezone = DateTimeZoneProviders.Tzdb["Australia/Brisbane"];

var zonedDateTime = thisNow.InZone(timezone);

// 构造双向可用的模式,使用和GeneralFormatOnlyIso一致的G格式串,绑定Tzdb时区提供者
var zonePattern = ZonedDateTimePattern.CreateWithInvariantCulture(
    "G", 
    DateTimeZoneProviders.Tzdb);

var zoneFormatted = zonePattern.Format(zonedDateTime);

var zoneParseResult = zonePattern.Parse(zoneFormatted);

Console.WriteLine(zoneParseResult.Success ? "parse success" : "parse failure");

运行上述代码即可得到预期的解析成功结果。

内容的提问来源于stack exchange,提问作者onefootswill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:48:02