Tryparse对我不起作用,并且ParseExact可以工作,但是在包含额外空间时失败:
//Tryparse
string dateTimeString = "Sep 10 08:19";
DateTime dateAndTime;
if (DateTime.TryParse(dateTimeString, out dateAndTime))
{
string temp = dateAndTime.ToString(); //"9/21/2018 10:08:00 AM" ??????? why?
}
//ParseExact works fine but it won't work with extra spaces in the date
string format = "MMM d HH:mm";
//dateTimeString = "Sep 10 08:19"; //works fine with this string
dateTimeString = "Sep 9 08:19"; //notice extra extra space between "Sep" and "9"
dateAndTime = DateTime.ParseExact(dateTimeString, format, System.Globalization.CultureInfo.InvariantCulture); //Exception here
string temp2 = dateAndTime.ToString();
有什么想法吗?谢谢
答案 0 :(得分:3)
所以第一件事是您应该使用TryParseExact()
而不是ParseExact()
,因为这是与TryParse()
相当的比较方法。
接下来,您只需要向方法中传递一个额外的参数,即DateTimeStyles
值DateTimeStyles.AllowWhiteSpaces
:
if(DateTime.TryParseExact(
"Sep 10 08:19",
"MMM d HH:mm",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out dateAndTime))
{
//Parsed correctly, do something
}
提琴here