开发者

Validating dates in aspnet mvc

开发者 https://www.devze.com 2023-03-19 15:25 出处:网络
I have my ViewModel on which I\'ve defined my properties; one of them is a DateTime field defined as:

I have my ViewModel on which I've defined my properties; one of them is a DateTime field defined as:

    [DisplayName("Data")]
    [DataType(DataType.Date)]        
    [Required(ErrorMessage="Selezionare una data")]
    [DisplayFormat(ApplyFormatInEditMode = true,  DataFormatString = "{0:dd/MM/yyyy}" )]
    public DateTime? DtNews { get;set; }

When I submit the form I always receive the error m开发者_运维技巧sg "The value '13/07/2011' is not valid for DtNews" because the system swaps days and months ... I need to have dd/mm/yyyy format.


You could set the culture in your web.config to some culture for which the date format is dd/MM/yyyy. For example that's the case with it-IT:

<globalization culture="it-IT" uiCulture="it-IT"/>

By default the culture is set to auto. This means that ASP.NET uses the browser settings in order to deduce the culture of the client. So if the browser is configured to use en-US, then the format for dates will be MM/dd/yyyy.

Another possibility is to set the format for the current thread culture:

var dtfi = (DateTimeFormatInfo)Thread.CurrentThread.CurrentCulture.DateTimeFormat.Clone();
dtfi.ShortDatePattern = "dd/MM/yyyy";
dtfi.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture.DateTimeFormat = dtfi;
Thread.CurrentThread.CurrentUICulture.DateTimeFormat = dtfi;
0

精彩评论

暂无评论...
验证码 换一张
取 消