Alvin Caseria Alvin Caseria - 1 year ago 197
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

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") + " " +

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") + " " +


string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " +

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 Source

try this below

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download