I am getting a json message from a server and I am trying to parse it into C# objects. I am using the RestSharp Deserializer. There is one field that is not properly converting into a datetime:
the string value of the field in this message is:
"createDateTime":"Mon Oct 07 00:00:00 EDT 2013"
on my object I have this as:
public DateTime? createDateTime { get; set; }
NOTE: that is a nullable DateTime because something the field is blank
but when I do this:
var deSerializer = new JsonDeserializer();
var response = client.Execute(request);
var responseObj = _deSerializer .Deserialize<Response>(response);
return responseObj;
I realized the root cause is that the DateTime.Parse is failing. I tried adding this which causes it to use
DateTime.ParseExact()
_deserializer.DateFormat = "ddd MMM dd HH:mm:ss zzz yyyy";
but I then get an error stating:
String was not recognized as a valid DateTime.
so this all comes down to how in C# to parse a date coming in as this format
Mon Oct 07 00:00:00 EDT 2013
since in my case I don't really care about time and the timezone is always in EDT, i wrote this to get around this issue in the short term.
private DateTime? ParseMe(string s)
{
var split = s.Split(new[] {' '},StringSplitOptions.RemoveEmptyEntries);
var year = int.Parse(split[split.Count()-1]);
var day = int.Parse(split[2]);
var month = split[1];
int monthInDigit = DateTime.ParseExact(month, "MMM", CultureInfo.InvariantCulture).Month;
return new DateTime(year, monthInDigit, day);
}