首页 > 解决方案 > C# 和 SQL 服务器之间的 DateTime 不匹配

问题描述

我像这样在 C# 中创建 DateTime

DateTime oDate = Convert.ToDateTime(xate);

返回22/09/2020 01:27:00 ب.ظ}

并在保存后将其保存在 SQL Server 中我看到存储的时间很奇怪

在此处输入图像描述

当我尝试运行这样的 SQL 命令时

INSERT INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098','22/09/2020 12:00:00 ق.ظ', '22/09/2020 12:00:00 ق.ظ'); 

我收到这个错误

从字符串转换日期和/或时间时转换失败。

我发现在 C# 中生成的时间与 SQL Server 中的格式相反。

我不知道如何将 C# 中的 DateTime 保存到 SQL Server。

我在 SQL Server 中保存数据时间的代码是:

HomeVisitRow homeVisit = BehzistiDb2.List<HomeVisitRow>().Where(x => x.LifeplusCaseId == lifeplusCaseId && x.FromDateTime <= oDate && x.ToDateTime > oDate).FirstOrDefault();

if (homeVisit == null)
{
    homeVisit = new HomeVisitRow
    {
        Id = Guid.NewGuid(),
        LifeplusCaseId = lifeplusCaseId,
        FromDateTime = oDate,
        ToDateTime = oDate.AddMonths(6) 
    };

    BehzistiDb2.Insert<HomeVisitRow>(homeVisit);

标签: c#sqlsql-server

解决方案


从字符串转换日期和/或时间时转换失败

问题是您将字符串' '插入 SQL 数据库,而不是像您指定的 DateTime 对象。

如果我们使用,我们可以很容易地从一个字符串创建一个 DateTime 对象DateTime.TryParseExact()

例子:

DateTime fromDate;
string txtStartDate = "22/09/2020 01:27:00";
DateTime.TryParseExact(txtStartDate, "dd/MM/yyyy HH:mm:ss", 
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None, out fromDate);

Console.WriteLine(fromDate.ToString());

现在我们也可以将该变量作为它的值插入到我们的 SQL 语句中。

INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098', fromDate, toDate);

推荐阅读