![](/img/trans.png)
[英]System.FormatException: String was not recognized as a valid DateTime
[英]String was not recognized as a valid DateTime FormatException
我收到錯誤消息的異常 -
“System.FormatException:字符串未被識別為有效的日期時間。”
在以下行中:
DateTime RecDate = RecDateSearch == string.Empty ? Convert.ToDateTime("1/1/1970").Date : Convert.ToDateTime(RecDateSearch).Date;
When choose day in the date less than 12 like 10/1/2021 or 12/12/2020, I get no exception. But when choose day in the date more than 12 like 20/1/2020 or 23/12/2020, I get this exception.
這是我的 javascript 代碼 -
var myTable = $('#m_table_1').DataTable({ "processing": true, "serverSide": true, "dom": '<"top"i>rt<"bottom"lp><"clear">', "scrollY": 200, "scrollX": true, "ajax": { "url": '@Url.Action("AllPOSDonations", "POSDonation")', "type": "POST" }, columns: [ { data: "Id" }, { data: "No" }, { data: "DonationDate", render: function (d) { return moment(d).format('YYYY/MM/DD'); }
這是我的 razor 代碼 -
<div class="form-group" id="datepickerDiv"> <input type="text" id="recDate" class="form-control" data-date-container='#datepickerDiv' /> </div>
將日期和時間的指定字符串表示形式轉換為其等效的 DateTime。 字符串表示的格式必須與指定的格式完全匹配,否則將拋出異常
使用DateTime.ParseExact
DateTime date = DateTime.ParseExact(RecDateSearch, "dd/MM/yyyy", null);
我收到錯誤消息的異常 -
“System.FormatException:字符串未被識別為有效的 DateTime。”
在以下行:
DateTime RecDate = RecDateSearch == string.Empty ? Convert.ToDateTime("1/1/1970").Date : Convert.ToDateTime(RecDateSearch).Date;
When choose day in the date less than 12 like 10/1/2021 or 12/12/2020, I get no exception. But when choose day in the date more than 12 like 20/1/2020 or 23/12/2020, I get this exception.
這是我的 javascript 代碼 -
var myTable = $('#m_table_1').DataTable({ "processing": true, "serverSide": true, "dom": '<"top"i>rt<"bottom"lp><"clear">', "scrollY": 200, "scrollX": true, "ajax": { "url": '@Url.Action("AllPOSDonations", "POSDonation")', "type": "POST" }, columns: [ { data: "Id" }, { data: "No" }, { data: "DonationDate", render: function (d) { return moment(d).format('YYYY/MM/DD'); }
這是我的 razor 代碼 -
<div class="form-group" id="datepickerDiv"> <input type="text" id="recDate" class="form-control" data-date-container='#datepickerDiv' /> </div>
當您為日期值提供格式正確的字符串時,使用更寬容的Parse
方法,您可以減少為:
DateTime RecDate = RecDateSearch == string.Empty ? new DateTime(1970, 1, 1) : DateTime.Parse(RecDateSearch);
Console.WriteLine(RecDate.ToString("yyyy/MM/dd"));
結果:
string RecDateSearch = string.Empty;
// RecDate -> 1970-01-01
string RecDateSearch = "2020/01/20";
// RecDate -> 2020-01-20
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.