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

尝试两种格式解析指定日期字符串失败,求正确解析方法

解决日期字符串解析失败的问题

你的解析失败主要有两个核心原因:

  • 未指定英文文化信息:日期里的Sat(星期缩写)、May(月份缩写)是英文格式,若系统默认文化为非英文,会无法识别这些英文缩写。
  • 时区格式字符串不匹配:+0000这种4位带符号的时区偏移,对应的格式符是zzzz,而非zzz(zzz对应+00:00这种带冒号的时区格式)。

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

string dateString = "Sat May 27 03:03:50 +0000 2023";
// 使用zzzz匹配+0000格式的时区,同时指定英文文化信息
string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
var englishCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");

if (DateTime.TryParseExact(dateString, format, englishCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out DateTime dateTime))
{
    Console.WriteLine(dateTime);
}
else
{
    Console.WriteLine("Invalid date string");
}

如果需要完整保留时区偏移信息,建议使用DateTimeOffset代替DateTime,避免丢失时区数据:

string dateString = "Sat May 27 03:03:50 +0000 2023";
string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
var englishCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");

if (DateTimeOffset.TryParseExact(dateString, format, englishCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out DateTimeOffset dateOffset))
{
    Console.WriteLine(dateOffset);
}
else
{
    Console.WriteLine("Invalid date string");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:24:58