some image

Scribes, Tests & More...

MVC and the Date Field Dilemma

Web Development
4/27/2014 (PST)

ASP.NET MVC and Entity Framework play well together. It's the pesky web browsers that are still learning how to interpret HTML 5 date types. Do we use RFC, or ISO standard dates? What format is best? Should the users device current culture settings decide how to display things like dates, numbers, decimal numbers, currency?

Date and Time interpretation is specified in RFC 3339

Research shows that the current Chrome web browser expects an input element decorated with the type="date" attribute and a date value in the format "yyyy-MM-dd". This format is case sensitive.

This type="date" attribute tells Chrome to render a calendar popup for the user. 

The problem we experience as the end user of a browser like IE is a displayed date format of 2014-12-31, which affects everyone viewing your page, regardless of their regional settings. 

Initially, some clever JavaScript was used to format the date in MM/DD/YYYY format, however, different regions use different formats, so we want to provide a culturally correct rendering as much as is possible.

I found a solution posted on StackOverflow posted by Blerton Hoxta, which is quite practical and elegant, to say the least. It is extensible, so we can check for different browser types and specify cultural sensitive dates as well.

I am posting the code here as well as linking to the OP.  Thank you Blerton.

@modelNullable<DateTime>
@usingSystem.Globalization;

@{
DateTime dt =DateTime.Now;

if(Model!=null)
{ dt =(System.DateTime)Model;
}

if(Request.Browser.Type.ToUpper().Contains("IE")||Request.Browser.Type.Contains("InternetExplorer"))
{
@Html.TextBox("",String.Format("{0:d}", dt.ToShortDateString()),new{@class="datefield", type ="date"})
}
else{ //Tested in chromeDateTimeFormatInfo dtfi =CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat; dtfi.DateSeparator="-"; dtfi.ShortDatePattern=@"yyyy/MM/dd";

@Html.TextBox("",String.Format("{0:d}", dt.ToString("d", dtfi)),new{@class="datefield", type ="date"})
}
}
blog comments powered by Disqus