C# 该字符串未被识别为有效的 DateTime(格式)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17870854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The string was not recognized as a valid DateTime (Formatting)
提问by Zzz
I am trying to convert a Oracle DateTime
field into a string (TextBox
). However I keep getting the following error:
我正在尝试将 OracleDateTime
字段转换为字符串 ( TextBox
)。但是我不断收到以下错误:
The string was not recognized as a valid DateTime.
该字符串未被识别为有效的 DateTime。
The value in the field is: 7/25/2013 4:12:18 PM
该字段中的值为: 7/25/2013 4:12:18 PM
Code:
代码:
DateTime dt = DateTime.ParseExact("MM/dd/yyyy HH:mm:ss tt",dr["category"].ToString().Trim(), CultureInfo.InvariantCulture);
txtFedCat.Text = dt.ToString("dd/M/yyyy");
采纳答案by fcuesta
Try this:
尝试这个:
DateTime dt = DateTime.ParseExact(dr["category"].ToString().Trim(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
The first parameter to ParseExact is the date string, and the second, the format. You had it the other way around. Also I think you want to use the following format specifiers:
ParseExact 的第一个参数是日期字符串,第二个参数是格式。你反过来了。此外,我认为您想使用以下格式说明符:
- M : The month, from 1 through 12.
- d : The day of the month, from 1 through 31.
- h : The hour, using a 12-hour clock from 1 to 12.
- M : 月份,从 1 到 12。
- d:一个月中的第几天,从 1 到 31。
- h :小时,使用从 1 到 12 的 12 小时制。
回答by fulvio
var dateString = "7/25/2013 4:12:18 PM";
DateTime dt = DateTime.ParseExact(dateString, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
var txtFedCat = dt.ToString("dd/M/yyyy");
回答by Roya
you can do this:
你可以这样做:
string strDate = DateTime.ParseExact(yourDateTime, "M/d/yyyy h:mm:ss tt", null).ToString();
if (strDate.Substring(0, 10).Trim().LastIndexOf(" ", System.StringComparison.Ordinal) == 8)
strDate = strDate.Substring(0, 8).Trim();
else
strDate = strDate.Substring(0, 10).Trim();
DateTime FinalDate = Convert.ToDateTime(strDate);