Max
Max

Reputation: 1299

Tryparse not working for me and ParseExact works but it fails when extra space is included

Tryparse not working for me and ParseExact works but it fails when extra space is included:

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

Any ideas? Thanks

Upvotes: 1

Views: 157

Answers (1)

maccettura
maccettura

Reputation: 10819

So first thing is you should use TryParseExact() instead of ParseExact() since that is the right comparable method to TryParse().

Next you just need to pass in an extra parameter to your method, The DateTimeStyles value DateTimeStyles.AllowWhiteSpaces:

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

Fiddle here

Upvotes: 3

Related Questions