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?
<p class="time">@String.Format("{0:dd/MM/yyyy}",item.EndTime)</p>
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
在您的视图中使用ToString
方法:
<p class="time">@item.EndTime.ToString("d/M/yyyy")</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.