使用 C# 将日期时间格式转换为 SQL 格式 [英] DateTime format to SQL format using C#

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

问题描述

我正在尝试从 C# 中保存当前日期时间格式并将其转换为 SQL Server 日期格式,例如 yyyy-MM-dd HH:mm:ss 这样我就可以将它用于我的UPDATE 查询.

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.

这是我的第一个代码:

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

日期上的输出没问题,但时间总是12:00:00",所以我将代码更改为以下内容:

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 未处理

FormatException was unhandled

并建议我需要解析.因此,我尝试根据我在 StackOverflow 中的研究对我的代码执行此操作:

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

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

但它告诉我这是一种对给定上下文无效的方法.我尝试寻找我的问题的解决方案,但我已经被困了两个小时.我对 C# 还是有点陌生​​,你能帮帮我吗?

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?

推荐答案

在下面试试这个

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

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

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