Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No overload for method 'ToString" takes 1 arguments when casting date

I am trying to save a date from my Angular ui-Datepicker to my SQL database. The date is in the format (10-27-2015 12:00 AM) but it will not save. I tried using the following to convert it to SQL DateTime format:

    DateTime? myDate = form.dteStartDate;
    string sqlFormattedDate = myDate.ToString("yyyy-MM-dd HH:mm:ss");

But I receive the error "No overload for method 'ToString' takes 1 arguments. The field in SQL is type 'datetime'.

Any assistance is greatly appreciated.

like image 589
Rani Radcliff Avatar asked Oct 05 '22 20:10

Rani Radcliff


2 Answers

You want to use DateTime.ToString(format) not Nullable<DateTime>.ToString(no overload):

DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate.Value.ToString("yyyy-MM-dd HH:mm:ss");

Of course this doesn't handle the case that there is no value. Perhaps something like this:

string sqlFormattedDate = myDate.HasValue 
    ? myDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
    : "<not available>";
like image 157
Tim Schmelter Avatar answered Oct 08 '22 09:10

Tim Schmelter


The most immediate way to do this is to write:

DateTime? myDate = form.dteStartDate;    
string sqlFormattedDate = myDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "N/A";

adding ? after myDate will check if it is not null, and with the ?? you will handle the case in which the variable is null.

like image 8
antoprd Avatar answered Oct 08 '22 08:10

antoprd