![](/img/trans.png)
[英]Is there any difference between DateTime in c# and DateTime in SQL server?
[英]Mismatches on DateTime between C# and SQL server
我像這樣在 C# 中創建 DateTime
DateTime oDate = Convert.ToDateTime(xate);
返回22/09/2020 01:27:00 ب.ظ}
保存后將其保存在 SQL 服務器中 我看到存儲的時間很奇怪
當我嘗試像這樣運行 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 服務器中的格式相反。
我不知道如何將C#中的DateTime保存到SQL服務器。
我在 SQL 服務器中保存數據時間的代碼是:
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 Object 。
如果我們使用DateTime.TryParseExact()
,我們可以輕松地從字符串創建 DateTime Object
例子:
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);
您可以根據您的要求格式化日期,請參閱以下示例。
DateTime oDate = Convert.ToDateTime(xate);
oDate = oDate.ToString("yyyy-MM-dd");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.