繁体   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