Alvin Caseria Alvin Caseria - 4 months ago 41
SQL Question

datetime format to SQL format using C#

I am trying to save the current date time format from C# and convert it to a SQL Server date format like so

yyyy-MM-dd HH:mm:ss
so I can use it for my
Update
query.

This was my first code:

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


The output on date is ok but time is always "12:00:00" so I changed my code to the following:

string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " +
myDateTime.TimeOfDay.ToString("HH:mm:ss");


It gave me a compile error "FormatException was unhandled" and suggested I need to parse. So I tried doing this to my code as per my research here in staackoverflow:

string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " +
myDateTime.Parse.TimeOfDay.ToString("HH:mm:ss");


or

string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " +
myDateTime.tryParse.TimeOfDay.ToString("HH:mm:ss");


but it's giving me it's a method which is not valid for given context. I tried searching for solutions to my problem and currently stuck for two hours now. I'm still a bit new in C#, can you help please?

Answer

try this below

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