使用C#日期时间格式到SQL格式 [英] datetime format to SQL format using C#

查看:139
本文介绍了使用C#日期时间格式到SQL格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图挽救从C#当前日期和时间格式,并将其转换为SQL Server的日期格式,像这样 YYYY-MM-DD HH:MM:SS 等等我可以用它为我的更新查询。

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.

这是我第一次code:

This was my first code:

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

这是迄今为止的输出是不错,但时间总是12:00:00,让我改变了我的code以下内容:

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

这给了我一个编译错误FormatException了未处理,并建议我需要解析。于是,我就在这里staackoverflow这样做是为了我的code按我的研究:

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

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

但它给我,它是不是有效的给定上下文的方法。我试图寻找我的问题的解决方案,目前滞留了两个小时了。我仍然在C#中有些新的,你能帮助吗?

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?

推荐答案

试试这个下面

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

这篇关于使用C#日期时间格式到SQL格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆