I have created a class that maps to my database model. One of the properties is StartDate
public DateTime? StartDate { get; set; }
I can easily grab this while building my model and place it in my view.
What I would like to do is have the view show a more friendly date MM/dd/yyyy. I'm aware of the .ToString(MM/dd/yyyy) and have attempted to use properties to set it. I'm having troubles because the database is set as a nullable DateTime and I'd like to return a string. Maybe I'm not using the correct approach
Code to retrieve from db
var newsItem = (from n in context.News
where n.NewsID == id
select new Models.Components.NewsModel
{
NewsId = n.NewsID,
Header = n.Header,
MainPhoto = n.MainImage,
Text = n.Text,
Date = n.CreatedDate,
Active = n.Active,
StartDate = n.StartDate,
EndDate = n.EndDate
}).FirstOrDefault();
Trying to set the value
private DateTime? _StartDate { get; set; }
public string StartDate
{
get
{
DateTime tmp;
DateTime.TryParse(_StartDate.ToString(), out tmp);
return tmp.ToString("MM/dd/yyyy");
}
set { _StartDate = value; }
}
This complains because _StartDate is a DateTime? value
What is the most efficient way to display the date in the format I specified?
I assume NewsModel is some kind of view model. In which case you can just decorate your property with some data annotations:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime StartDate { get; set; }
In order for this to work, you need to make use of the HTML helpers:
@Html.DisplayFor(m => m.StartDate)
If you want to do this format to also be applied when you use any HTML editor helper (e.g. Html.EditorFor, Html.TextBoxFor, ...), you also need to specify ApplyFormatInEditMode = true for the DisplayFormat attribute. So the property would end up being decorated as follows:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
Update
So after some discussion in chat, it seems the annotations within MVC 4 behave a little differently than with MVC 3. Specifically, with the above annotations for MVC 3, the following HTML would be rendered:
<input class="text-box single-line" id="StartDate" name="StartDate"
type="text" value="11/15/2013" />
However, with MVC 4, there's a slight difference:
<input class="text-box single-line" id="StartDate" name="StartDate"
type="date" value="11/15/2013" />
Notice that it changes the input type to date. This was causing a datepicker to automatically be shown in Chrome, which was undesired behaviour.
The problem here is that the date formatting will be applied via Html.EditorFor, but not with Html.TextBoxFor. Html.TextBoxFor can be passed CSS classes to change the behaviour, but Html.EditorFor doesn't have that kind of overload.
For possible solutions to this, see this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With