Tryparse对我不起作用并且ParseExact可以工作,但是当包含额外空间时它会失败

时间:2018-09-21 19:06:27

标签: c# datetime parsing tryparse

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

有什么想法吗?谢谢

1 个答案:

答案 0 :(得分:3)

所以第一件事是您应该使用TryParseExact()而不是ParseExact(),因为这是与TryParse()相当的比较方法。

接下来,您只需要向方法中传递一个额外的参数,即DateTimeStylesDateTimeStyles.AllowWhiteSpaces

if(DateTime.TryParseExact(
   "Sep 10 08:19", 
   "MMM d HH:mm", 
   CultureInfo.InvariantCulture, 
   DateTimeStyles.AllowWhiteSpaces, 
   out dateAndTime))
{
    //Parsed correctly, do something
}

提琴here