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

C#.NetAngularjsDatetime

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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>";

Solution 2 - C#

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.

Solution 3 - C#

It will work fine.

DateTime? strDate = form.dteStartDate;
strDate.Value.ToString("yyyy-MM-dd HH:mm tt");

Solution 4 - C#

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

Also if you can use server-side code in .cshtml and manage this casting as below (for example):

   <label>Establish: @(((DateTime)Model.EstablishDate).ToString("yyyy-MM-dd"))</label>

Solution 5 - C#

Another way is adding question mark behind "myDate" variable.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRani RadcliffView Question on Stackoverflow
Solution 1 - C#Tim SchmelterView Answer on Stackoverflow
Solution 2 - C#antoprdView Answer on Stackoverflow
Solution 3 - C#Md Nazrul IslamView Answer on Stackoverflow
Solution 4 - C#ElnazView Answer on Stackoverflow
Solution 5 - C#Son CaoView Answer on Stackoverflow