简体   繁体   English

将字符串转换为日期时间C#

[英]Convert String to Date Time C#

I'm new to c# how can I convert my input string in to DateTime. 我是C#的新手,如何将输入字符串转换为DateTime。

_toDate = 5/22/2015

I cannt use 我不能使用

DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);

Or 要么

Convert.ToDateTime(_toDate)

throw an exception String was not recognized as a valid DateTime. 引发异常字符串未被识别为有效的DateTime。

Note : String shold be excact the same as above. 注意:字符串保留与上述相同。

Appreciate your reply 感谢您的回覆

Clearly, your string and format does not match. 显然,您的字符串和格式不匹配。

From documentation ; 文件 ;

Converts the specified string representation of a date and time to its DateTime equivalent. 将指定的日期和时间的字符串表示形式转换为其等效的DateTime。 The format of the string representation must match a specified format exactly . 字符串表示形式的格式必须与指定的格式完全匹配。

You need to use M/dd/yyyy with a culture that has / as a DateSeparator like InvariantCulture . 您需要将M/dd/yyyy/作为DateSeparator的文化一起使用,例如InvariantCulture

string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);

When you use null as an IFormatProvider , it's threaded as your CurrentCulture and if your CurrentCulture doesn't have / as a DateSeparator , you will get FormatException because / custom format specifier has a special meaning as replace me with current culture or supplied culture date separator . 当您将null用作IFormatProvider ,它将作为您的CurrentCulture线程化,如果您的CurrentCulture没有/作为DateSeparator ,则将得到FormatException因为/自定义格式说明符具有特殊含义,因为用当前区域性或提供的区域性日期分隔符替换我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM