[英]String was not recognized as a valid DateTime server error
下面是我的代碼
var result =
(from SV in Tbl
where (DateTimeOffset.Parse(SV.FieldName) >= DateTimeOffset.Parse(StartDate)
&& DateTimeOffset.Parse(SV.FieldName) <= DateTimeOffset.Parse(EndDate))
group SV by 1 into SVgrp
select new { Count = SVgrp.Sum(p => p.Count) }).ToList()
SV.FieldName = '19-06-2015'
的值SV.FieldName = '19-06-2015'
, StartDate = '2015-09-20T00:00:00Z'
, EndDate = '2015-10-21T23:59:59Z'
在我的開發機器上,此代碼可以完美運行,而在我的服務器上,它給我的錯誤String was not recognized as a valid DateTime
我的兩台機器都將日期格式設置為英語(印度),將位置設置為印度,並將時區設置為UTC。
我嘗試在所有四個Parse方法上添加CultureInfo.InvariantCulture
,但是錯誤沒有消失。
為什么我僅在服務器上收到此錯誤? 如何解決?
我確定轉換s.FieldName = '19 -06-2015'的值時會出現錯誤。 編譯器假定格式為MM-dd-yyyy,因此19被視為無效的月份號。
我的建議是構造日期值,請參見下文
var result = (from SV in Tbl
where (new DateTime(Convert.ToInt32(SV.FieldName.Substring(6, 4)), Convert.ToInt32(SV.FieldName.Substring(3, 2)), Convert.ToInt32(SV.FieldName.Substring(0, 2))) >= DateTimeOffset.Parse(StartDate)
&& new DateTime(Convert.ToInt32(SV.FieldName.Substring(6, 4)), Convert.ToInt32(SV.FieldName.Substring(3, 2)), Convert.ToInt32(SV.FieldName.Substring(0, 2))) <= DateTimeOffset.Parse(EndDate))
group SV by 1 into SVgrp
select new { Count = SVgrp.Sum(p => p.Count) }).ToList()
這不是最好的方法,但可以完成任務。
嘗試使用DateTime.ParseExact(dateString,@“ d / M / yyyy”,System.Globalization.CultureInfo.InvariantCulture);
要么
DateTime.TryParse(dateString,out date4);
如果解析失敗,則不會引發錯誤,而是返回false表示解析失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.