[英]Formatting a date using C# in an MVC3 application
I have a model with a DateTime property: 我有一个带有DateTime属性的模型:
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 确保您的View可以看到ExtensionMethods类,并在需要时添加“使用”语句
在您的视图中使用ToString
方法:
<p class="time">@item.EndTime.ToString("d/M/yyyy")</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.