C# 日期的范围属性

C# 日期的范围属性,c#,data-annotations,date-range,asp.net-mvc-5.2,displayattribute,C#,Data Annotations,Date Range,Asp.net Mvc 5.2,Displayattribute,我让这个类重写Range属性: public class RangeDateAttribute : RangeAttribute { public RangeDateAttribute() : base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(), DateTime.Today.ToShortDateString()) { } } 我的属性的DataAnnotation: [R

我让这个类重写Range属性:

public class RangeDateAttribute : RangeAttribute
{
    public RangeDateAttribute()
        : base(typeof(DateTime),
    DateTime.Now.AddYears(-20).ToShortDateString(), DateTime.Today.ToShortDateString()) { }
}
我的属性的DataAnnotation:

[RangeDate(ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime anyDate { get; set; }
[RangeDate(ErrorMessage = "Value for {0} must be between {1:dd/MM/yyyy} and {2:dd/MM/yyyy}")]
public DateTime anyDate { get; set; }
我在验证中使用了[ToSortDateString()]方法,但是当显示错误时,它会随时间而来。。例:

Value for anyDate must be between 26/05/1995 00:00:00 and 26/05/2015 00:00:00
我怎样才能解决这个问题


谢谢。

您必须使用ArgumentException(String)方法格式化错误消息,并应用与短日期相关的格式化规范,如String.format(“{0:d}”,dt)。希望这能有所帮助。非常感谢,

您可以在错误消息属性上使用一些格式:

[RangeDate(ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime anyDate { get; set; }
[RangeDate(ErrorMessage = "Value for {0} must be between {1:dd/MM/yyyy} and {2:dd/MM/yyyy}")]
public DateTime anyDate { get; set; }

很有魅力,非常感谢!顺便说一句,我不需要在那个类中使用ToSortDateString(),对吗?只是在错误消息中..您仍然需要使用ToSortDateString()或ToString()方法将DateTime转换为字符串,因为参数数据类型仅接受字符串。此外,您可能希望将最大参数的时间值设置为23:59:59,而不是00:00:00,以包括一整天,您可以使用:DateTime.Today.ToString(“dd/MM/yyyy 23:59:59”)来完成此操作。快乐编码!