Title

Saturday, 17 January 2015

String to date parsing error “String was not recognized as a valid DateTime.”


In my property below I m parsing string to datetime.

public virtual string StartTimeLocal  {   set { StartTime = DateTime.Parse(value).ToUTCDateTime(); }  }

Just checked in value I have 26/1/2014 02:17 PM

Can you please help me what wrong I m doing and how to correct it ?

Answer

DateTime.Parse parses standart date and time formats. Your string is not one of them.

You can use DateTime.TryParseExact or DateTime.ParseExact methods instead.

string s = "26/1/2014 02:17 PM";  DateTime dt;  if(DateTime.TryParseExact(s, "dd/M/yyyy hh:mm tt",   CultureInfo.GetCultureInfo("en-US"),   DateTimeStyles.None, out dt))  {   Console.WriteLine(dt);  }  else  {   //Your string is not a valid DateTime.  }
Answer2

Your input is formatted using en-US culture settings, so you should either make sure your application runs on system with local culture set to en-US or specify culture explicitly:

public virtual string StartTimeLocal  {   set { StartTime = DateTime.Parse(value, CultureInfo.GetCultureInfo("en-US")).ToUTCDateTime(); }  }
Answer3

Try the below:

CultureInfo provider = CultureInfo.InvariantCulture;  format = "dd/MM/yyyy hh:mm tt";  result = DateTime.ParseExact(dateString, format, provider);

No comments:

Post a Comment