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?
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.
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.
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 ?
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With