c# - 如何正确地将日期时间从 c# 传递到 sql?

标签 c# sql datetime

我有一个表格,其中的日期时间格式为:

2011-07-01 15:17:33.357

当我在对象上执行 .ToString() 时,我正在使用 c# DateTime 我正在获取格式为 DateTime 的对象:

04/07/2011 06:06:17

我想知道如何正确传递正确的 DateTime,因为当我运行代码中的 SQL 时它不起作用(即选择正确的 DateTime)。我无法使用 SQL 事件探查器。

这是代码:

//looks to if a user has had any activity in within the last time specified
        public bool IsUserActivitySinceSuppliedTime(int userId, DateTime since)
        {
            //get everything since the datetime specified [usually 5 hours as this is 
            //how long the session lasts for
            string sql = "SELECT * FROM tbl_webLogging WHERE userid = @userid AND DateAdded > @sinceDateTime";

            SqlParameter sinceDateTimeParam = new SqlParameter("@sinceDateTime", SqlDbType.DateTime);
            sinceDateTimeParam.Value = since;

            SqlCommand command = new SqlCommand(sql);
            command.Parameters.AddWithValue("@userid", userId);
            command.Parameters.Add(sinceDateTimeParam);


            using (SqlDataReader DataReader = GetDataReader(command))
            {
                if (DataReader.HasRows)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }


        }

更新*********************

我对数据运行了以下命令:

SELECT * FROM tbl_webLogging 
WHERE userid = 1 
AND DateAdded > '2011-07-01 07:19:58.000'

SELECT * FROM tbl_webLogging 
WHERE userid = 1 
AND DateAdded > '04/07/2011 07:19:58'

一个返回 53 条记录,另一个返回 69 条记录。怎么会这样?当我将 DateTime (04/07/2011 07:19:58) 从 C# 传递到 SQL 时,根本没有显示任何记录!

最佳答案

您已经通过使用 DateTime 中的值的 DateTime 参数正确地完成了它,所以它应该/strong> 已经工作了。忘记 ToString() - 因为这里没有使用它。

如果有差异,很可能是两个环境的精度不同;也许选择一个舍入(秒,也许?)并使用它。还要记住 UTC/local/unknown(DB 没有日期“种类”的概念;.NET 有)。

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

请注意,数据库中的日期时间 不是任何此类格式;那只是你的查询客户端向你展示善意的谎言。它存储为一个数字(甚至这是一个实现细节),因为人类有一种奇怪的倾向,不会意识到您显示的日期与 40723.6371916281。愚蠢的人类。通过将其简单地视为“日期时间”,您应该不会遇到任何问题。

关于c# - 如何正确地将日期时间从 c# 传递到 sql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6570621/

相关文章:

c# - 在 .NET 中将整个数据库从一台服务器复制到另一台服务器

c# - 如何处理 Entity Framework 中的陈旧缓存?

php - 如何保存用户的过滤条件?

javascript - 需要将新日期与日期选择器进行比较

c# - 有哪些技术可用于发送短信?

c# - 调用 SysFreeString() 时出现堆损坏错误

组合两个表的Sql查询

mysql - 如何减少单个查询中冗余的MySQL函数调用?

Java jsr310 : difference between dates and times

夏令时更改期间的 Java Calendar.roll 和 CST