[英]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#? 从C#中的“9:00 PM”等字符串格式解析小时和AM / PM值的最有效方法是什么?
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. 请参阅自定义日期和时间格式字符串,以便从各种格式的DateTime值获取信息。
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: 使用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. 编辑 :自上午12点失败后的小时删除了%12。
begin pseudocode: 开始伪代码:
DateTime dt;
if (!DateTime.TryParse("9:00 AM", out dt))
{
//error
}
end pseudocode 结束伪代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.