簡體   English   中英

解析DateTime和時間(字符串)

[英]Parse DateTime With Time (string)

嘗試從QueryString的兩個部分一起解析日期(DateTime)和時間(string)時,我收到“格式錯誤”錯誤。

任何幫助解決此問題表示贊賞。 謝謝!

var EventStartDate = Convert.ToDateTime(Request.QueryString["date"]);
string EventStartTime = Request.QueryString["time"];

DateTime newDateTime = 
  EventStartDate.Add(TimeSpan.ParseExact(EventStartTime, "H:mm:ss", null));

下面有更多詳細信息...

EventStartDate = 3/5/2016 12:00:00 AM

EventStartTime = 8:00:00 PM

Error:
Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error: 
Line 8:          string EventStartTime = Request.QueryString["time"];
Line 9:  
Line 10:         DateTime newDateTime = EventStartDate.Add(TimeSpan.ParseExact(EventStartTime, "hh:mm:ss", null));

您錯過了HH 請使用HH而不是H 希望它能工作。

DateTime newDateTime = 
  EventStartDate.Add(TimeSpan.ParseExact(EventStartTime, "HH:mm:ss", null));

假設您的時間格式為00:00:00 ,請嘗試此操作

DateTime newDateTime = EventStartDate.Add(TimeSpan.ParseExact(EventStartTime, "hh\\:mm\\:ss", null));

Convert.ToDateTime使用CurrentCulture設置的標准日期和時間格式。 看起來像是3/5/2016 12:00:00 AM不是其中之一。 另外,您的CurrentCulture 可能具有AMDesignatorPMDesignator屬性為空字符串。

您可以將DateTime.ParseExact與自定義格式和特定​​的區域性設置結合使用,例如

var EventStartDate = DateTime.ParseExact(Request.QueryString["date"], 
                                         "M/d/yyyy hh:mm:ss tt",
                                         CultureInfo.InvariantCulture);

您說您的EventStartTime8:00:00 PM並且嘗試將其解析為TimeSpan但是由於TimeSpan是一個時間間隔,因此這些指示符對它們沒有任何意義,因此也不支持它們作為輸入格式。

如果您的字符串中確實有這些指示符,則需要像這樣將其刪除;

string EventStartTime = Request.QueryString["time"].Replace("AM", "")
                                                   .Replace("PM", "").Trim();

然后您可以將其解析為TimeSpan

var StartTime = TimeSpan.Parse(EventStartTime, CultureInfo.InvariantCulture);

最后,將其添加到您的EventStartDate

var newDateTime = EventStartDate.Add(StartTime);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM