将12小时时间格式转换为24小时整数?

时间:2013-06-12 03:17:50

标签: c# .net vb.net string parsing

在我的应用程序中,我有一个字符串下拉框,显示12小时内可供用户选择的小时数。可能的值是:

9am
10am
11am
12pm
1pm
2pm
3pm
4pm
5pm

什么代码会将其中一个字符串转换为24小时整数?例如,10am应转换为104pm应转换为16

4 个答案:

答案 0 :(得分:11)

您可以使用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​​的上下文。

答案 1 :(得分:2)

如果您有一个下拉列表,为什么不将这些值设置为您想要的整数值:

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

答案 2 :(得分:1)

考虑到时间是连续的,您可以简化逻辑:

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案例,因为在“am”之后12小时的性质是一秒钟。

答案 3 :(得分:1)

你可以使用DateTime.Parse,但这不适合国际化。

int hour = DateTime.Parse(stringValue).Hour;

相反,只需在DateTime中使用ComboBox个对象,然后使用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
}