0

Im trying send date in format dd/mm/yyyy as query string parameter but binding for date property not working for me, only if I send date US format mm/dd/yyyy , any idea how to solve?

hooliday
  • 25
  • 3

2 Answers2

1

Generally, we solve this situation by using Custom model binding.

You can see my code example below.

Action:

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

DateTimeModelBinder:

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

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

Result: enter image description here

Yinqiu
  • 6,609
  • 1
  • 6
  • 14
0

Another solution would be to send your date in UTC format. For example:

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

Then ASP.Net Core will bind it automatically. Using UTC format is also considered a good practice. You easily cast your date object to UTC string using

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"); 

Source

Or in JavaScript

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

Source

Morasiu
  • 1,204
  • 2
  • 16
  • 38