3

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

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

什么代码会将这些字符串之一转换为 24 小时整数?例如,10am应该转换为104pm应该转换为16.

4

4 回答 4

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 的上下文。

于 2013-06-12T03:23:58.927 回答
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>
于 2013-06-12T03:33:18.017 回答
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导致问题的情况,因为 12 小时的性质是“am”之后的一秒。

于 2013-06-12T03:24:45.270 回答
1

You could use DateTime.Parse, but that would not play nicely with internationalization.

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

Instead, just use DateTime objects in the ComboBox and format them using 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
}
于 2013-06-12T03:32:48.563 回答