且构网

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

将DateTime字符串转换为Datetime

更新时间:2023-02-03 07:58:25

使用重载的方法之一System.DateTime.ParseSystem.DateTime.ParseExact.

-SA
Use one of the overloaded methods System.DateTime.Parse or System.DateTime.ParseExact.

—SA


使用DateTime.TryParse方法.

方法是这样的:

Use DateTime.TryParse method.

This is how it is done:

DateTime dateTime;

DateTime.TryParse(strDateTime, out dateTime);



最酷的部分是TryParse如果解析成功将返回True,如果解析失败则返回False.您可以在if条件下使用该语句.


更新1:



The coolest part is TryParse will return True if the parsing is successful and return False if the parsing fail. You can either use the statement in a if condition.


Update 1:

shan1395写道:
shan1395 wrote:

DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);

DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);



此代码是将字符串转换为DateTime的方法之一.如果您使用Convert.ToDateTime
,则不需要使用TryParse.
如果字符串为空,则Convert.ToDateTime将失败并引发异常.但是TryParse不会引发异常.

解决方案1:



This code is one of the ways to convert string to DateTime. It is not required to use TryParse if you use Convert.ToDateTime

Convert.ToDateTime will fail and throw exception if the string is empty. But TryParse will not throw exception.

Solution 1:

DateTime dateTime = System.Convert.ToDateTime(item.StartDate);





解决方案2:



or

Solution 2:

DateTime dateTime;

DateTime.TryParse(item.StartDate, out dateTime);



如果有帮助,请将其标记为答案



Mark it as answer if it is helpful