且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串转换为日期时间?

更新时间:2023-01-30 18:38:56

Google发现 DateTime.TryParseExact Method(System) | Microsoft Docs [ ^ ],以微秒为单位。
Google found DateTime.TryParseExact Method (System) | Microsoft Docs[^] in microseconds.


DateTime myDate = DateTime.ParseExact("2013-02-11T14:29:01", "yyyy'-'MM'-'dd'T'HH':'mm':'ss", System.Globalization.CultureInfo.InvariantCulture);





我使用了2013-02-11T14:29:01而不是2013-02-11T14:29:01-05:00及其显示日期时间要求。



谢谢



I have used 2013-02-11T14:29:01 instead of 2013-02-11T14:29:01-05:00 and its showing date time as per the requirement.

Thank You


string nodeValue = "2013-02-11T14:29:01-05:00";
	DateTime result = DateTime.Parse(nodeValue);
	Console.WriteLine(result);





2/11/2013 1:29:01 PM



请注意,如果字符串不是有效日期,则会抛出异常

在这种情况下使用TryParse



2/11/2013 1:29:01 PM

Be aware that if the string is not a valid date an exception will be thrown
in that case use TryParse

ring nodeValue = "2013-13-11T14:29:01-05:00";
	DateTime result;
	 DateTime.TryParse(nodeValue, out result);
	Console.WriteLine(result);





1/0001 12:00:00 AM



1/0001 12:00:00 AM