Reputation: 36723
I have a model with a DateTime property:
public DateTime EndTime { get; set; }
In my controller, I assign that property to a value returned from my database:
aModel.EndTime = auction.EndTime.Value;
And in my View:
<p class="time">@item.EndTime</p>
Currently the date is returned as:
9/12/2011 --> Month / Day / Year
I want it to display as:
12/9/2011 --> Day / Month / Year
I'm sure the application is displaying the date according to the servers settings, but I do not wish to change that. How can I display the date like I want to in the second example?
Upvotes: 2
Views: 2484
Reputation: 48415
The quick and easy way...
<p class="time">@item.EndTime.ToString("dd/MM/yyyy")</p>
I would suggest you store the format string as a config value though so you can easily change it later... or add a way for the user to set their preference
Maybe even do some extension method work...
Helper class
public static class ExtensionMethods
{
public static string ToClientDate(this DateTime dt)
{
string configFormat = System.Configuration.ConfigurationManager.AppSettings["DateFormat"];
return dt.ToString(configFormat);
}
}
Config File
<appSettings>
<add key="DateFormat" value="dd/MM/yyyy" />
</appSettings>
View
<p class="time">@item.EndTime.ToClientDate()</p>
Make sure you View can see the ExtensionMethods class, add a "Using" statement if needed
Upvotes: 2
Reputation: 67352
Use the ToString
method in your view:
<p class="time">@item.EndTime.ToString("d/M/yyyy")</p>
Upvotes: 1