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

75,630

Solution 1

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

It will work fine.

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

Solution 3

 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 4

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 5

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

DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate?.ToString("yyyy-MM-dd HH:mm:ss");
Share:
75,630
Rani Radcliff
Author by

Rani Radcliff

Updated on July 08, 2022

Comments

  • Rani Radcliff
    Rani Radcliff almost 2 years

    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.