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

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.


It will work fine.

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

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

 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>