3

私のアプリには、ユーザーが選択できる 12 時間制の時間を示す文字列のドロップダウン ボックスがあります。可能な値は次のとおりです。

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

これらの文字列の 1 つを 24 時間の整数に変換するコードはどれですか? たとえば、10amに変換する必要があり、 に変換する10必要4pmがあります16

4

4 に答える 4

2

If you have a dropdown, why not set the values to be the integer values you desire:

<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

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 に答える