Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

DateTime format to SQL format using C#

I am trying to save the current date time format from C# and convert it to an 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 okay, 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 this 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 StackOverflow:

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 telling me that it's a method which is not valid for given context. I tried searching for solutions to my problem and I have been stuck for two hours now. I'm still a bit new in C#, can you help me please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this below

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...