Convert String to Nullable DateTime [duplicate]

北战南征 提交于 2019-12-12 09:28:24

问题


Possible Duplicate:
How do I use DateTime.TryParse with a Nullable<DateTime>?

I have this line of code

DateTime? dt = Condition == true ? (DateTime?)Convert.ToDateTime(stringDate) : null;

Is this the correct way to convert string to Nullable DateTime, or is there a direct method to convert without converting it to DateTime and again casting it to Nullable DateTime?


回答1:


You can try this:-

 DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);



回答2:


You are able to build a method to do this:

public static DateTime? TryParse(string stringDate)
{
    DateTime date;
    return DateTime.TryParse(stringDate, out date) ? date : (DateTime?)null;
}



回答3:


DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));



回答4:


Simply assigned without cast at all :)

DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;


来源:https://stackoverflow.com/questions/13247273/convert-string-to-nullable-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!