Search code examples
c#stringstring-parsing

Parse hour and AM/PM value from a string - C#


What would be the most effective way to parse the hour and AM/PM value from a string format like "9:00 PM" in C#?

Pseudocode:

string input = "9:00 PM";

//use algorithm

//end result
int hour = 9;
string AMPM = "PM";

Solution

  • Try this:

    string input = "9:00 PM";
    
    DateTime result;
    if (!DateTime.TryParse(input, out result))
    {
        // Handle
    }
    
    int hour = result.Hour == 0 ? 12 
               : result.Hour <= 12 ? result.Hour 
               : result.Hour - 12;
    string AMPM = result.Hour < 12 ? "AM" : "PM";