如何将格式为MMMdyyyyhhmmtt的datetime字符串转换为datetime对象?

编程入门 行业动态 更新时间:2024-10-27 17:09:45
本文介绍了如何将格式为MMMdyyyyhhmmtt的datetime字符串转换为datetime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试过如下:

DateTime.ParseExact("Feb520161000PM", "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)

但是它给了 FormatException 。

有趣的是

DateTime.ParseExact(DateTime.Now.ToString("MMMdyyyyhhmmtt"), "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)

这也是给格式异常

推荐答案

Alexei的回答是对的,如果你让我,我想解释一点点..

Alexei's answer is quite right, I wanna explain little bit deep if you let me..

你在想 5 应该符合 d 说明符,对吧?但这不是如何 DateTime.ParseExact 工作在引擎盖下。

You are thinking 5 should match with d specifier, right? But this is not how DateTime.ParseExact works under the hood.

由于 d自定义格式说明符代表 1 code> 31 ,此说明符将在您的字符串中映射 52 ,不只需 5 。这就是为什么你的代码抛出 FormatException 。

Since The "d" custom format specifier represents number from 1 through 31, this specifier will map 52 in your string, not just 5. That's why your code throws FormatException.

正如你所看到的,你的字符串格式不能解析除非使用它进行一些字符串操作。

As you can see, your string format can't parsed unless you do it some string manipulations with it.

在这种情况下,.NET Team 建议使用两个数字格式,例如 05 ,或插入分隔符以用于日期和时间值。

In such a case, .NET Team suggests either using two digit forms like 05 or insert separators for your date and time values.

您可以创建一个自定义方法,解析仅限 的 MMMdyyyhhmmtt 格式解析此类格式的字符串, p>

You can create a custom method that parse this MMMdyyyyhhmmtt format for only parse this kind of formatted strings like;

public static DateTime? ParseDate_MMMdyyyyhhmmtt(string date) { if (date == null) return null; if (date.Length < 14) return null; if (date.Length == 14) date = date.Insert(3, "0"); DateTime dt; if (DateTime.TryParseExact(date, "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) return dt; return null; }

更多推荐

如何将格式为MMMdyyyyhhmmtt的datetime字符串转换为datetime对象?

本文发布于:2023-11-22 15:24:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   如何将   格式为   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!