将12小时时间格式转换为24小时整数
本文关键字:24小时 整数 转换 格式 12小时 时间 | 更新日期: 2023-09-27 18:18:02
在我的应用程序中,我有一个字符串下拉框,显示可能的小时在12小时的时间供用户选择。可能的值为:
9am
10am
11am
12pm
1pm
2pm
3pm
4pm
5pm
什么代码将这些字符串转换为24小时整数?例如,将10am
转换为10
,将4pm
转换为16
您可以使用DateTime. parse(…)来获取DateTime值,然后为结果引用.Hour
属性;
int h = DateTime.Parse("10am").Hour; // == 10
int h2 = DateTime.Parse("10pm").Hour; // == 22
DateTime。Parse允许的内容相当自由,但显然在内部做了一些假设。例如,在上面的代码中,DateTime.Parse("10am")
返回当前时区的当前日期上午10点(我想…)。因此,要注意使用API的上下文。
如果您有一个下拉菜单,为什么不将值设置为您想要的整数值:
<asp:DropDownList runat="server" ID="hours">
<asp:ListItem Value="9">9am</asp:ListItem>
<asp:ListItem Value="10">10am</asp:ListItem>
<!-- etc. -->
<asp:ListItem Value="17">5pm</asp:ListItem>
</asp:DropDownList>
考虑时间是连续的,可以简化逻辑:
var firstHourStr = box.Items[0].ToString();
var firstHour = int.Parse(firstHourStr.Replace("am", "").Replace("pm", ""));
if (firstHourStr.Contains("pm"))
{
firstHour += 12;
}
var selectedHour = firstHour + box.SelectedIndex;
如果小时是静态的,并且您知道第一个小时,则可以使用const并使用var selectedHour = FIRST_HOUR + box.SelectedIndex
大大简化过程。
同样,我假设了问题中所示的有效格式。
最后注意:您需要处理12pm
的情况下,这将导致问题,由于小时12的性质是一秒钟之后"am"。
您可以使用DateTime.Parse
,但这对国际化来说不是很好。
int hour = DateTime.Parse(stringValue).Hour;
相反,只需在ComboBox
中使用DateTime
对象并使用FormatString:
// In Constructor:
cbHours.Items.Add(new DateTime(2000, 1, 1, 8, 0, 0));
cbHours.Items.Add(new DateTime(2000, 1, 1, 10, 0, 0));
cbHours.Items.Add(new DateTime(2000, 1, 1, 13, 0, 0));
cbHours.FormatString = "h tt";
// In event handler
if (cbHours.SelectedIndex >= 0)
{
int hour = ((DateTime)cbHours.SelectedItem).Hour
// do things with the hour
}