简体   繁体   English

C# - 如何实现DateTime.TryParse 24小时时间格式

[英]C# - How to implement DateTime.TryParse for 24 hour time format

Could someone demonstrate how you could implement DateTime.TryParse into my current code which takes in intergers. 有人可以演示如何将DateTime.TryParse实现到我当前的代码中,这会占用整数。 For example a 24 hour time format 23:00 例如24小时时间格式23:00

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

    if (int.TryParse(textBox2.Text, out numberEntered))
    {
         if (numberEntered < 1 || numberEntered > 28)
         {
              MessageBox.Show("");
              textBox2.Text = 5.ToString();
         }
    }
    else
    {
         MessageBox.Show("");
         textBox2.Text = 5.ToString();
    }
}

This should do what you want: 这应该做你想要的:

    void textBox1_Validating(object sender, CancelEventArgs e)
    {
        DateTime dateEntered;

        if (DateTime.TryParseExact(textBox1.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
        {
            MessageBox.Show(dateEntered.ToString());
        }
        else
        {
            MessageBox.Show("You need to enter valid 24hr time");
        }

    }

I would recommend doing some reading up on the various parameters available for DateTime.TryParseExact , and choosing the ones that match your situation with care. 我建议您阅读一些可用于DateTime.TryParseExact的各种参数,并选择符合您情况的参数。 Also have a look at the values of actual DataTime objects that get generated by this parse, since they will have a Date part as well - if you use this data later on (particularly for comparing these times) these details could prove important. 还要查看由此解析生成的实际DataTime对象的值,因为它们也将具有Date部分 - 如果稍后使用此数据(特别是为了比较这些时间),这些细节可能非常重要。

string strDate = "23:00";
string format = "HH:mm";
DateTime res;
bool success = DateTime.TryParseExact(strDate, format, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out res);

hi guys am posting for first time.. it works for me.. 嗨伙计们第一次发帖..它对我有用..

DateTime dtSurgStartTime;
bool blnStart = DateTime.TryParseExact(txtSURGERY_START_DATE_TIME.Text, @"dd/MM/yyyy HH:mm", null,
System.Globalization.DateTimeStyles.None, out dtSurgStartTime);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM