I have reviewed the answer to Parse very long date format to DateTime in C# and it goes a little way to fixing my problem, but I fear I might be stumbling into an unrelated issue, and thus have opened this new thread.
Dates come into my process as a string that I have no control over. They always represent a date in the future. An example would be "Wednesday 26th November at 18:30
". Notice, the day has an ordinal, and that there is no year.
I need to get these into a DateTime
structure, so that I can... well, do DateTime
things to them!
I am currently using the following snippet (adjusted from the afore mentioned question), but it's still failing on the last conditional, which I would expect it to pass.
public DateTime ParseOrdinalDateTime(string dt)
{
DateTime d;
if (DateTime.TryParseExact(dt, "dddd d\"st\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
return d;
if (DateTime.TryParseExact(dt, "dddd d\"nd\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
return d;
if (DateTime.TryParseExact(dt, "dddd d\"rd\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
return d;
if (DateTime.TryParseExact(dt, "dddd d\"th\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
return d;
throw new InvalidOperationException("Not a valid DateTime string");
}
If you're receiving a 24h format time, then you should parse the string as "dddd d\"th\" MMMM \"at\" HH:mm"
(notice the uppercase Hs).
1) Swap the hh:mm to HH:mm (using 24 hours..)
2) Set culture to en-US
Such as
string dateString = "Wednesday 26th November at 18:30";
string format = "dddd d\"th\" MMMM \"at\" HH:mm";
DateTime dt;
DateTime.TryParseExact(dateString, format, new CultureInfo("en-US"), DateTimeStyles.AssumeLocal, out dt);
edit - formatted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With