Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:

DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d); 

the compiler tells me

'out' argument is not classified as a variable

Not sure what I need to do here. I've also tried:

out (DateTime)d.Value  

and that doesn't work either. Any ideas?

like image 988
Brian Sullivan Avatar asked Oct 10 '08 16:10

Brian Sullivan


People also ask

Can DateTime be nullable?

DateTime itself is a value type. It cannot be null.

How do you make a date time nullable?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

How does DateTime TryParse work?

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

What is DateTime TryParse?

The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true if the conversion was successful and false if otherwise.


2 Answers

As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:

public static DateTime? TryParse(string text) {     DateTime date;     if (DateTime.TryParse(text, out date))     {         return date;     }     else     {         return null;     } } 

... or if you like the conditional operator:

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

Or in C# 7:

public static DateTime? TryParse(string text) =>     DateTime.TryParse(text, out var date) ? date : (DateTime?) null; 
like image 159
Jon Skeet Avatar answered Nov 03 '22 00:11

Jon Skeet


DateTime? d=null; DateTime d2; bool success = DateTime.TryParse("some date text", out d2); if (success) d=d2; 

(There might be more elegant solutions, but why don't you simply do something as above?)

like image 40
Jason Kealey Avatar answered Nov 02 '22 23:11

Jason Kealey