在我的 ASP.NET MVC 5 dwith EF 6 项目中,我有一个数据库,其中日期时间格式存储为字符串,如“dd-MM-yyyy”。用户可以随时更改此格式。用户将在 View 的日期字段中使用给定的格式。但是他们什么时候会发布。它将自动绑定(bind)为该属性的 DateTime。我通过以下代码静态处理它
[DataType(DataType.Time), DisplayFormat(DataFormatString = "{HH:mm}", ApplyFormatInEditMode = true)]
public DateTime? EndingTime { get; set; }
public string EndingTimeValue
{
get
{
return EndingTime.HasValue ? EndingTime.Value.ToString("HH:mm") : string.Empty;
}
set
{
EndingTime = DateTime.Parse(value);
}
}
但我知道这不是最好的方法。可能需要模型绑定(bind)器或过滤器或任何类型的自定义属性。如果您给我一个带有示例代码的有效解决方案,我将得到很大帮助。提前致谢。
注意:我正在使用 Razor View 引擎。我的解决方案包含 7 个项目。所以没有机会在模型中使用 Session 。同样,我有一个用于使用 Entity Framework 的基本存储库类。
最佳答案
人们通常将日期时间作为日期时间存储在数据库中。 然后,无论您在哪里进行从日期时间到字符串的转换,该日期时间都可以以取决于查看者文化的格式显示。 通过这样做,您可以快速制作一个具有日期时间格式的页面,无论您身在何处,都可以很好地格式化日期时间。
更改传递给 toString 的文化,格式也会更改。
请看这个MSDN page有关它的更多信息。
编辑:(见下面的评论) 服务器上的任何位置:
string WhatYouWant = yourTime.ToCustomFormat()
并为日期时间创建一个扩展方法,从数据库中获取格式并返回正确格式的字符串。
public static class MyExtensions
{
public static string ToCustomFormat(this DateTime yourTime)
{
// Get the following var out of the database
String format = "MM/dd/yyyy hh:mm:sszzz";
// Converts the local DateTime to a string
// using the custom format string and display.
String result = yourTime.ToString(format);
return result;
}
}
这将允许您随时随地在您的服务器上调用它。您无法在 javascript 中访问方法客户端。我希望这会有所帮助。
(老实说我也是一个新开发者,还有很多东西要学^^)
关于c# - ASP.NET MVC 如何处理来自数据库的动态日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194272/