[英]How to parse string into datetime format
I want to parse a date-time string into a DateTime
data type. 我想将日期时间字符串解析为DateTime
数据类型。
The format of the string is like 08/10/2013 09:49 PM
, and I want it to go to the form 2013-10-08 21:49:05.6500000
字符串的格式类似于2013-10-08 21:49:05.6500000
08/10/2013 09:49 PM
,我希望它使用表格2013-10-08 21:49:05.6500000
The following is my code but it's not working. 以下是我的代码,但无法正常工作。
public static DateTime ConvertDateTime(String arg_dateTime)
{
try
{
return DateTime.ParseExact(arg_dateTime,
"dd/MM/yyyy H:m:s fff",
System.Globalization.CultureInfo.InvariantCulture);
}
catch(Exception exp)
{
return DateTime.Now;
}
}
Your format string doesn't match your input data. 您的格式字符串与输入数据不匹配。 Try a format string of "dd/MM/yyyy HH:mm:ss tt"
, and see the custom date and time format documentation for more information. 尝试使用格式字符串"dd/MM/yyyy HH:mm:ss tt"
,有关更多信息,请参见自定义日期和时间格式文档 。
Note that rather than catching an exception if it fails, you should use DateTime.TryParseExact
and check the return value. 请注意,您应该使用DateTime.TryParseExact
并检查返回值,而不是在失败时捕获异常。 Or if a failure here represents a big failure, just use ParseExact
and don't catch the exception. 或者,如果此处的故障表示ParseExact
故障,则只需使用ParseExact
而不捕获异常。 Do you really want to default to DateTime.Now
? 您真的要默认为DateTime.Now
吗? It seems unlikely to me. 对我来说似乎不太可能。 You should strongly consider just letting the exception propagate up. 您应该强烈考虑让异常传播出去。
Also, your method doesn't return a particular format - it returns a DateTime
. 同样,您的方法不返回特定格式-它返回DateTime
。 That doesn't know anything about a format - if you want to convert the value to a specific format, you should do so specifically. 那对格式一无所知-如果您想将值转换为特定格式,则应专门这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.