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?
Asked
Active
Viewed 766 times
0

hooliday
- 25
- 3
-
Hi @hooliday,any update about this case? – Yinqiu Nov 20 '20 at 13:04
2 Answers
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

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");
Or in JavaScript
new Date('05 October 2011 14:48 UTC').toISOString();

Morasiu
- 1,204
- 2
- 16
- 38