简体   繁体   English

ASP.NET MVC如何处理数据库中的动态日期时间格式

[英]ASP.NET MVC How to handle dynamic datetime format from database

In my ASP.NET MVC 5 dwith EF 6 project, I have a database where datetime format is stored as string like "dd-MM-yyyy". 在我的带有EF 6的ASP.NET MVC 5 d项目中,我有一个数据库,其中日期时间格式存储为“ dd-MM-yyyy”之类的字符串。 User can change this format any time. 用户可以随时更改此格式。 User will use the given format in the date fields in the view. 用户将在视图的日期字段中使用给定的格式。 But when they will post that. 但是什么时候他们会发布。 Automatically it will bind as a DateTime for that property. 它会自动绑定为该属性的DateTime。 I am statically handling it by the following code 我通过以下代码静态处理它

[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);
    }
}

but I know it's not a best way to do that. 但我知道这不是最好的方法。 There may need a model binder or filter or any kind of custom attribute. 可能需要模型绑定器或过滤器或任何类型的自定义属性。 I will be greatly helped if you give me a efficient solution with sample code. 如果您提供带有示例代码的有效解决方案,将对我有很大帮助。 Thanks in advance. 提前致谢。

NB: I am using razor view engine. 注意:我正在使用剃刀视图引擎。 and my solution consists of 7 projects. 我的解决方案包含7个项目。 So there is no chance of using Session in model. 因此,没有机会在模型中使用Session。 Again I have a base repository class for using entity framework. 同样,我有一个使用实体框架的基本存储库类。

People usually store the datetime in the database as a datetime. 人们通常将日期时间作为日期时间存储在数据库中。 Then wherever you do a translation from datetime to string that datetime can be displayed in a format that depends on the culture of the viewer. 然后,无论您进行从日期时间到字符串的转换,该日期时间都可以根据查看器的区域性以一种格式显示。 By doing this you can quickly make a page with datetime formats that will format the datetimes nicely wherever you are. 这样,您可以快速创建一个具有日期时间格式的页面,无论您身在何处,都可以很好地格式化日期时间。

change the culture you pass to the toString and the format changes. 更改传递给toString的区域性,格式也会更改。

please see this MSDN page for more info about it. 请参阅此MSDN页面以获取有关它的更多信息。

edit: (see comments below) anywhere on server: 编辑:(请参阅下面的评论)在服务器上的任何位置:

string WhatYouWant = yourTime.ToCustomFormat()

and create an extension method for the datetime that gets the format out of the database and returns a string in the correct format. 并为datetime创建扩展方法,该方法将从数据库中提取格式并以正确的格式返回字符串。

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;
        }
    }   

This will allow you to call it anywhere anytime on your server. 这样您就可以在服务器上的任何位置调用它。 You can't access the method client side in javascript. 您无法在javascript中访问方法客户端。 I hope this helps. 我希望这有帮助。

(To be honest I'm a new developer too and still have a lot to learn ^^) (说实话,我也是一个新开发人员,仍然有很多东西要学习^^)

I have tried many options regarding this problem. 关于这个问题,我已经尝试了许多选择。 Now what I am doing is created an action filter to catch all the DateTime and nullable DateTime Fields. 现在,我正在创建一个动作过滤器,以捕获所有DateTime可空的DateTime字段。 Here I am providing the binder. 我在这里提供活页夹。

public class DateTimeBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);


        DateTime date;
        var displayFormat = SmartSession.DateTimeFormat;

        if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName,"Invalid Format");
        }


        return base.BindModel(controllerContext, bindingContext);
    }
}

in views the code I am formatting the date using same date format. 在视图中,代码我使用相同的日期格式来格式化日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM