为什么在 C# 中从字符串转换为日期时间失败

本文关键字:日期 时间 失败 转换 字符串 为什么 | 更新日期: 2023-09-27 17:56:28

我有一个这样的字符串,我想将其转换为DateTime格式(MM/dd/yyyyTHH:mm:ss)。但它失败了,请让我知道我错在哪里。

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string stime = "4/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

这是代码,我如何设置此字符串:

string startHH = DropDownList1.SelectedItem.Text;
string startMM = DropDownList2.SelectedItem.Text;
string startSS = DropDownList3.SelectedItem.Text;
string starttime = startHH + ":" + startMM + ":" + startSS;
string stime = StartDateTextBox.Text + "T" + starttime;

获取此异常

String was not recognized as a valid DateTime.

为什么在 C# 中从字符串转换为日期时间失败

您在格式字符串中写入了MM,这意味着您需要一个两位数的月份。如果您想要一位数的月份,只需使用 M .

DateTime dt = DateTime.ParseExact(stime, "M/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

另一种解决方案是更改字符串以匹配格式。

string stime = "04/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

这样做的关键是记住你正在精确地解析。因此,必须将字符串与格式完全匹配。

问题:在您的日期字符串4/17/2014T12:00:00中,您只有一位数Month值 (4),但在 DateFormat 字符串中您提到双MM

解决方案:您应该指定单M而不是双MM

试试这个:

DateTime dt = DateTime.ParseExact(stime, "M/dd/yyyyTHH:mm:ss", 
                              CultureInfo.InvariantCulture);
请注意,

您的日期字符串仅包含月份的 1 位数字,但您的模式定义了MM
因此,要么使用月份04,要么将模式更改为M