Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 277
Michael Kniskern Avatar asked Jun 29 '26 06:06

Michael Kniskern


1 Answers

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";
like image 76
ChaosPandion Avatar answered Jul 01 '26 20:07

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!