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";
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";
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";
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.
begin pseudocode:
DateTime dt;
if (!DateTime.TryParse("9:00 AM", out dt))
{
//error
}
end pseudocode
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.
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");
}