我像这样在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);
从字符串转换日期和/或时间时转换失败
问题是您将字符串' '
而不是指定的DateTime对象插入到SQL数据库中。
如果使用,我们可以很容易地从字符串创建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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句