简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM