2016-03-04 130 views
0

嘗試從QueryString的兩個部分一起解析日期(DateTime)和時間(字符串)時收到「錯誤格式」錯誤。使用時間解析日期時間(字符串)

任何幫助讚賞解決此問題。謝謝!下面

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)); 
+1

Request.QueryString [「date」]和Request.QueryString [「time」]'_exactly_?的值是什麼? –

+0

@SonerGönül感謝您的回覆。在原始文章的底部添加了上面的其他詳細信息。 –

回答

1

你已經錯過了HH。請使用HH而不是H。希望它能起作用。

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

試試這個假設你的時間格式爲00:00:00

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

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); 

你說你EventStartTime是​​,並嘗試將其解析到TimeSpan但是由於TimeSpan是一個時間間隔,這些代號有沒有與他們的意思,他們也不支持作爲輸入格式。

如果你的字符串確實有這些指示符,你需要刪除它們;

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

然後你可以解析它到TimeSpan像;

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

as last,add it to your EventStartDate like;

var newDateTime = EventStartDate.Add(StartTime);