views:

287

answers:

5

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";
+5  A: 

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";
ChaosPandion
You should add %12
Am
You should add formatting
Anon.
So I should post the same answer as everyone else?
ChaosPandion
@Chaos - I found a bug in your code. I have updated it with the fix
Michael Kniskern
@Michael - Appreciate it.
ChaosPandion
A: 

Use DateTime.Parse:

string input = "9:00 PM";
DateTime parsed = DateTime.Parse(input);
int hour = int.Parse(dt.ToString("h"));
string AMPM = parsed.ToString("tt");

Edit: Removed %12 on hour since that fails for 12 AM.

shf301
didn't want to change to (h-1)%12+1?
Jimmy
@Jimmy, that still fails for 12 AM, since the DateTime.Hour would return 0 and (0-1)%12+1 = 0 not 12.
shf301
ouch. Thats what I get for testing functions using Python. nevertheless +11 should be the same :P
Jimmy
A: 

begin pseudocode:

 DateTime dt;
 if (!DateTime.TryParse("9:00 AM", out dt))
 {
     //error
 }

end pseudocode

Steven A. Lowe
+1  A: 
string input = "9:00 PM";
DateTime dt = DateTime.Parse(input);

int hour = int.Parse(dt.ToString("hh"));
string AMPM = dt.ToString("tt");

See Custom Date and Time Format Strings for getting information from a DateTime value in all kinds of formats.

Rex M
why not: `int hour = dt.Hour;`?
Rubens Farias
@Rubens Farias `dt.Hour` returns 21, not 9.
Rex M
strange, I got 9..
Rubens Farias
@Rubens your code thinks the format is 9 AM, so dt.Hour is the 9th hour. The hour property always returns the nth hour of the day.
Rex M
@Rex, ty; I just found my bug: a capital `H` on format
Rubens Farias
@Rex - I get the following error "Input string was not in correct format" on `int hour = int Parse.(dt.ToString("h"))`
Michael Kniskern
@Michael what is `dt.ToString("h"))`?
Rex M
@Rex - I edited your answer to point out the error
Michael Kniskern
A: 

Try this:

DateTime result;
string input = "9:00 PM";

//use algorithm
if (DateTime.TryParseExact(input, "h:mm tt", 
    CultureInfo.CurrentCulture, 
    DateTimeStyles.None, out result))
{
    //end result
    int hour = result.Hour > 12 ? result.Hour % 12 : result.Hour;
    string AMPM = result.ToString("tt");
}
Rubens Farias