与其使用if(numberRentered24),还不如使用regex检查字段是否为24小时时钟格式,例如23:00。

private void textBox4_Validating(object sender, CancelEventArgs e)
{
    {
        int numberEntered;

        if (int.TryParse(textBox4.Text, out numberEntered))
        {
            if (numberEntered < 1 || numberEntered > 28)
            {
                MessageBox.Show("You have to enter a number between 1 and 28");
                textBox4.Text = 5.ToString();
            }
        }
        else
        {
            MessageBox.Show("You need to enter an integer (number)");
            textBox4.Text = 5.ToString();
        }
    }

最佳答案

string time = "23:00";
var time24 = new Regex(@"^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$");
bool is24hTime = time24.IsMatch(time);

可能有用,但我认为DateTime.TryParse是一条路要走。

08-16 00:23