gpt4 book ai didi

c# - 使用 AM/PM 标识符解析日期时间

转载 作者:行者123 更新时间:2023-11-30 16:10:12 25 4
gpt4 key购买 nike

我需要解析 Oct 3, 2014 10:05 a.m. 我熟悉使用 DateTime.TryParseExact() 使用 TT AM 或 PM 的表达式。但是,将其修改为 T.T. 不会成功地将 string 解析为 DateTime

这是我的代码:

string dateContent = "Oct 3, 2014 10:05 a.m.";
DateTime parseDate;
bool attempt = DateTime.TryParseExact(content, "MMM d, yyyy hh:mm T.T.", CultureInfo.CurrentCulture, DateTimeStyles.None, out parseDate);

如有任何帮助,我们将不胜感激。如果有任何遗漏或需要澄清,请告诉我。

最佳答案

如您所见,T.T. 格式不是标准格式 here , 所以我的建议是你用一个简单的方法摆脱它:

"Oct 3, 2014 10:05 a.m.".Replace("a.m.", "AM").Replace("p.m.", "PM");

更新

一个更通用的解决方案是使用如下正则表达式:

Regex.Replace(dateContent, "([a|p]).(m).", "$1$2", RegexOptions.IgnoreCase);

这应该可以解决问题(请注意,我附近没有 c# 编译器,但我还没有测试过)。这是为了查找模式 a.m.p.m.(忽略大小写)并替换为 ampm 的作用.

从那时起,TryParseExact 将起作用。

关于c# - 使用 AM/PM 标识符解析日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26224899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com