Skip to content

Instantly share code, notes, and snippets.

@benbrandt22
Created November 16, 2021 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbrandt22/a070f4398c075e6e6c77935f909159b3 to your computer and use it in GitHub Desktop.
Save benbrandt22/a070f4398c075e6e6c77935f909159b3 to your computer and use it in GitHub Desktop.
.Net core model binder for parsing dates from specific formats
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Demo.Web
{
public class CustomDateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(DateTime) || context.Metadata.ModelType == typeof(DateTime?))
{
return new CustomDateTimeModelBinder();
}
return null;
}
}
public class CustomDateTimeModelBinder : IModelBinder
{
private static readonly List<Type> SupportedDatetimeTypes =
new List<Type> { typeof(DateTime), typeof(DateTime?) };
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException (nameof(bindingContext));
}
if (!SupportedDatetimeTypes.Contains(bindingContext.ModelType))
{
return Task.CompletedTask;
}
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var dateTimeToParse = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(dateTimeToParse))
{
return Task.CompletedTask;
}
var formattedDateTime = ParseDateTime(dateTimeToParse);
bindingContext.Result = ModelBindingResult.Success(formattedDateTime);
return Task.CompletedTask;
}
private static DateTime? ParseDateTime(string date)
{
var customDatetimeFormats = new string[]
{
"yyyyMMddHHmmss",
"yyyyMMddHHmm",
"yyyyMMdd"
};
foreach (var format in customDatetimeFormats)
{
if (DateTime.TryParseExact(date, format, null, DateTimeStyles.None, out DateTime validDate))
{
return validDate;
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment