C# 将字符串转换为可空日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13247273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert String to Nullable DateTime
提问by Nalaka526
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 convertingit to DateTime and again castingit to Nullable DateTime?
这是一个字符串转换为可空的DateTime正确的方法,或者是有一个直接的方法来转换,而不将它DateTime和重新铸造它可空的DateTime?
采纳答案by Rahul Tripathi
You can try this:-
你可以试试这个:-
DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
回答by Matthew Layton
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));
回答by Han
Simply assigned without cast at all :)
简单分配,根本没有演员:)
DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;
回答by cuongle
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;
}

