How to convert datetime? to date

I need to fill out the txtb_dateOfService form, but if txtb_dateOfService is emapty, return null if not TryParse date > I had this error, I don’t know how to fix it.

The best overloaded method matching for 'System.DateTime.TryParse (string, outside of System.DateTime)' has some invalid arguments

  DateTime? dateOfService= null; if (string.IsNullOrEmpty(txtb_dateOfService.Text)) { dateOfService = null; } else if (DateTime.TryParse(txtb_dateOfService.Text, out dateOfService)) { } 
+4
source share
6 answers

Can't pass a link to a DateTime? into a method that expects a DateTime . You can solve this problem by entering a temporary variable, for example:

 else { // <<=== This is the final "else" from your code DateTime tmp; if (DateTime.TryParse(txtb_dateOfService.Text, out tmp)) { dateOfService = tmp; } else { dateOfService = null; } } 
+5
source

DateTime? your problem converting DateTime? in DateTime , not the other way around. The DateTime.TryParse out parameter is not NULL; if TryParse fails, the TryParse parameter will be set to DateTime.MinValue . It makes no sense to declare your dateOfService variable as a null type from this fragment.

+1
source

You can either throw an exception if the parsing fails:

 DateTime? dateOfService= null; if (string.IsNullOrEmpty(txtb_dateOfService.Text)) { dateOfService = null; } else { // will throw an exception if the text is not parseable dateOfService = DateTime.Parse(txtb_dateOfService.Text); } 

or use an intermediate DateTime to save the result:

 DateTime? dateOfService= null; if (string.IsNullOrEmpty(txtb_dateOfService.Text)) { dateOfService = null; } else { DateTime temp; if (DateTime.TryParse(txtb_dateOfService.Text, out temp)) { dateOfService = temp; } else { dateOfService = null; } } 

Any of them can be logically simplified; I am showing a complete breakthrough to convey logic.

+1
source

You can try converting string to DateTime

 DateTime? dataOfService = null; DateTime output; if (DateTime.TryParse(txtb_dateOfService.Text, out output)) dataOfService = output; 

now you can use dataOfService as a Nullable<DateTime> and check if it has valid data converted using the HasValue and Value properties.

0
source

you need to create a temporary value to hold out the TryParse parameter:

 DateTime tmp; if (DateTime.TryParse(txtb_dateOfService.Text, out tmp)) { dateOfService = tmp; } else{ dateOfService = null; } 

A shorter example

 DateTime tmp; DateTime? dateOfService = DateTime.TryParse(txtb_dateOfService.Text, out tmp) ? tmp : (DateTime?)null; 
0
source

try dateOfService.Value, this should work (I think)

0
source

All Articles