ParseExact does not process a string with a day, a date with a serial number, but without a year

I have reviewed the answer Parsing very long DateTime format in C # and it helps a little to fix my problem, but I'm afraid I stumbled into an unrelated issue and thus opened this new thread.

Dates enter my process as a string that I have no control over. They always represent the date in the future. An example would be " Wednesday 26th November at 18:30

". Please note: the day has a serial number and that there is no year.

I need to get them into a structure DateTime

so I can ... well, do with them DateTime

!

I'm currently using the following snippet (adjusted from the above question), but it still doesn't work on the last conditional I 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");
}

      

+3


source to share


3 answers


If you get a 24 hour time format then you should parse the string as "dddd d\"th\" MMMM \"at\" HH:mm"

(note the upper case Hs).



+3


source


1) Change hh: mm to HH: mm (using 24 hours ..)
2) Set culture to en-US

Such as the

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

      



code>

edit - format

+1


source


Your format string is slightly off and you need to set the culture:

private static void Main(string[] args)
{
    DateTime result = ParseOrdinalDateTime("Friday 29th August at 18:30");
}

public static DateTime ParseOrdinalDateTime(string dt)
{
    DateTime d;

    if (DateTime.TryParseExact(dt, "dddd d\"th\" MMMM \"at\" HH:mm",  CultureInfo.CreateSpecificCulture("en-GB"), DateTimeStyles.AssumeLocal, out d))
    {
        return d;
    }

    throw new InvalidOperationException("Not a valid DateTime string");
}

      

+1


source







All Articles