C#中的TextBox日期格式

时间:2013-03-09 06:19:05

标签: c# winforms date textbox

我想用作DatetimePicker。我想验证日期格式。我正在使用keypress事件进行验证。以下代码是在KeyPress事件中编写的。

 DateTime temp;
        if (DateTime.TryParse(textBox1.Text, out temp))
        { textBox1.Text = temp.ToShortDateString(); }
        else
        { errorProvider1.SetError(textBox1, "Format dd/MM/yyyy"); }

但在输入日期和月份后,它会自动给出年份,我也不希望这样。

用户可以输入完整日期。

3 个答案:

答案 0 :(得分:0)

尝试使用LostFocusLeave事件代替KeyPress事件。

答案 1 :(得分:0)

尝试以下Javascript代码:无需.Net实施:

function isValidDate(date){
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
        composedDate.getMonth() == m &&
        composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

使用此函数onKeyPress事件。如果没有工作评论。

此致..

答案 2 :(得分:0)

DateTime dt = DateTime.Now;
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
        if(DateTime.TryParse(textBox1.Text,out dt))
        {textBox1.Text =dt.ToShortDateString();}

在离开事件中它工作正常......,

相关问题