c# - 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);
解决方案
从字符串转换日期和/或时间时转换失败
问题是您将字符串' '
插入 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);
推荐阅读
- in-app-purchase - 在 ios 中重新购买自动续订订阅错误
- python - 编码标签熊猫时出现意外结果
- javascript - 比较具有相同属性的两个对象,但它混合在一起不遵循字母规则
- java - 使用 Apache Poi 重命名 XSSFTable 的标头会导致 XLSX 文件损坏
- angular - 为 @Input 设置默认值,以防它在离开时为空
- dart - Dart / Flutter:错误“流已被收听。” fa“for循环”中的&&“等待”失败
- java - @SpringBootTest 没有声明每个需要的类
- c# - 限制来自客户端的请求数
- sql - 从动态 sql 中选择非空列作为逗号分隔的字符串
- android - Google Play 控制台签名的 apk 版本代码错误