Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse doesn't accept nullable DateTime?

Tags:

c#

datetime

so I have this nullable variable I created:

private DateTime? _startDate;

I wanted to parse some variable to DateTime and then assign it to this variable, but the VS complains that the TryParse method has some invalid arguments.

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
        {
            DateTime.TryParse(Request.Form["StartDate"], out _startDate);
        }
        else
        { _startDate = null; }

Is there a syntax error I have or I can't use nullable variables in here?

like image 891
Victor Avatar asked Jan 26 '12 18:01

Victor


People also ask

What is the difference between datetime parse () and TryParse () methods?

The DateTime.TryParse (String, DateTime) method is similar to the DateTime.Parse (String) method, except that the TryParse (String, DateTime) method does not throw an exception if the conversion fails.

Why does TryParse () method fail when trying to format?

Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. The TryParse method can unexpectedly fail and return False if the current DateSeparator and TimeSeparator properties are set to the same value.

How to parse EndDate in datetime?

As EndDate is a nullable so you can parse it like that. DateTime.Parse (EndDate.Value.ToShortDateString () + " " + EndTime); DateTime.Parse (EndDate.GetValueOrDefault ().ToShortDateString () + " " + EndTime); I normally use default (DateTime?) and you'll also need to cast to a nullable DateTime object: return EndDate.HasValue ?

What is type type DATETIME%?

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time.


1 Answers

As others have said, they're not compatible types. I would suggest you create a new method which wraps DateTime.TryParse and returns a Nullable<DateTime>:

// Add appropriate overloads to match TryParse and TryParseExact
public static DateTime? TryParseNullableDateTime(string text)
{
    DateTime value;
    return DateTime.TryParse(text, out value) ? value : (DateTime?) null;
}

Then you can just use:

_startDate = Helpers.TryParseNullableDateTime(Request.Form["StartDate"]);

(No need to check for null or empty string; TryParse will just return false in that case anyway.)

like image 111
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet