使用时间解析日期时间(字符串)

问题描述:

尝试从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感谢您的回复。在原始文章的底部添加了上面的其他详细信息。 –

你已经错过了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); 

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