验证C#中的DateTime [英] Validate a DateTime in C#

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

问题描述

我怀疑我是唯一提出这个解决方案的人,但是如果你有一个更好的解决方案,请张贴在这里。我只想在这里留下这个问题,所以我和其他人可以稍后搜索。



我需要知道一个有效的日期是否已经输入到一个文本框中,这是我想出的代码。当焦点离开文本框时,我会触发此消息。

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


解决方案

  DateTime.TryParse 

这相信是更快,这意味着你不必使用丑陋的尝试/ catches:)



eg

  DateTime temp; 
if(DateTime.TryParse(startDateTextBox.Text,out temp))
// yay
else
// :(
/ pre>

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 :)

e.g

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
//yay
else
// :(

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

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