【问题标题】:Date binding dd-mm-yyyy in ASP NET Core 3.1ASP NET Core 3.1 中的日期绑定 dd-mm-yyyy
【发布时间】:2020-11-19 08:48:18
【问题描述】:

我尝试以dd/mm/yyyy 格式发送日期作为查询字符串参数,但绑定日期属性对我不起作用,只有当我发送日期美国格式 mm/dd/yyyy 时,知道如何解决?

【问题讨论】:

  • 嗨@hooliday,关于这个案例有什么更新吗?

标签: asp.net-core data-binding


【解决方案1】:

一般我们使用Custom model binding来解决这种情况。

您可以在下面查看我的代码示例。

行动:

    [HttpGet]
    public object Demo([ModelBinder(BinderType = typeof(DateTimeModelBinder))] DateTime MyTime)
    {
        return Ok();
    }

日期时间模型绑定器:

 public class DateTimeModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }
        var valueProviderResult = bindingContext.ValueProvider.GetValue("MyTime");

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        var value = valueProviderResult.FirstValue;

        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }
       
        var TestTime = DateTime.ParseExact(value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        bindingContext.Result = ModelBindingResult.Success(TestTime);
      
        return Task.CompletedTask;
    }
}

网址:https://localhost:xxxx/api/xxx/?mytime=19/05/2020

结果:

【讨论】:

    【解决方案2】:

    另一种解决方案是以 UTC 格式发送您的日期。例如:

    "2020-11-19T10:21:05Z"
    

    然后 ASP.Net Core 会自动绑定它。使用 UTC 格式也被认为是一种好的做法。您可以使用

    轻松地将日期对象转换为 UTC 字符串
    string foo = yourDateTime.ToUniversalTime()
                             .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"); 
    

    Source

    或者在 JavaScript 中

    new Date('05 October 2011 14:48 UTC').toISOString();
    

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多