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.
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>";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With