c# - 将字符串转换为 DateTime 格式

标签 c# datetime

我正在尝试使用以下方法将 09/01/2015 00:00:00 解析为 yyyy-MM-ddThh:mm:ssZ 格式:

DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);

但我得到 String was not recognized as a valid DateTime

谁能告诉我为什么?我相信 09/01/2015 00:00:00 是有效的 DateTime 格式?

最佳答案

来自 DateTime.ParseExact

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.

在您的情况下,它们不是。

我假设您的 09 部分是天数,您可以改用 dd/MM/yyyy HH:mm:ss 格式。

var dt = DateTime.ParseExact("09/01/2015 00:00:00", 
                             "dd/MM/yyyy HH:mm:ss", 
                             CultureInfo.InvariantCulture);

因为 CultureInfo 已经 implements IFormatProvider,您不需要显式转换它。

I don't understand this. So it means I first have to correct my string and secondly I can do a ParseExact(). I thought ParseExact could handle the given string...

ParseExact 不是一种可以解析您提供的任何 格式字符串的神奇方法。如果您的字符串和格式根据您使用的文化设置完全匹配,它只能处理。

关于c# - 将字符串转换为 DateTime 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35039646/

相关文章:

c# - 创建 GeoJson c#

c# - 类中的类,实例化为单个对象

c# - ASP.NET 站点和 SharePoint 站点有什么区别?

sql-server - 如何获得多个日期时间值的总和?

python - 正在解决 ValidationError : [u "'' value has an invalid date format. 它必须采用 YYYY-MM-DD 格式。”] 在 Django 1.9.2 中?

python - 在python中相互添加datetime.time对象

c# - 使用属性路由为 Web Api 在 View 中构造 url

c# - 硬盘或硬盘的序列号

python - "type object ' datetime.datetime ' has no attribute ' datetime '"即使是"import datetime"

java - 使用 Java-8 LocaldateTime 比较 future 三天的日期和时间