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

巧了我就是萌 提交于 2019-12-06 07:26:17
ChaosPandion

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!