如何在 C# 中验证日期时间? [英] How to Validate a DateTime in C#?

查看:38
本文介绍了如何在 C# 中验证日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑我是唯一提出此解决方案的人,但如果您有更好的解决方案,请在此处发布.我只是想把这个问题留在这里,以便我和其他人以后可以搜索它.

I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.

我需要判断是否在文本框中输入了有效日期,这是我想出的代码.当焦点离开文本框时,我会触发它.

I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box.

try
{
    DateTime.Parse(startDateTextBox.Text);
}
catch
{
    startDateTextBox.Text = DateTime.Today.ToShortDateString();
}

推荐答案

DateTime.TryParse

我相信这更快,这意味着您不必使用丑陋的尝试/捕获:)

This I believe is faster and it means you dont have to use ugly try/catches :)

例如

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
  // Yay :)
}
else
{
  // Aww.. :(
}

这篇关于如何在 C# 中验证日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆