Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ParseExact not parsing string with day, date with ordinal but no year

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");
}
like image 220
belial Avatar asked Sep 19 '25 19:09

belial


2 Answers

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).

like image 191
Arturo Torres Sánchez Avatar answered Sep 21 '25 10:09

Arturo Torres Sánchez


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

like image 22
tglanz Avatar answered Sep 21 '25 11:09

tglanz