1

I am struggling to get the right date format in ASP.NET Core 2.1. I have already various solutions for several hours and simply can't get it to work. Things I have tried so far:

  • Setting the culture in Startup.cs ConfigureServices class:

    // Add localization
    services.AddLocalization(options => options.ResourcesPath = "Resources");
    
    services.Configure<RequestLocalizationOptions>(
    opts =>
    {
        var supportedCultures = new List<CultureInfo>
        {
    
                new CultureInfo("nl-NL"),
        };
    
        opts.DefaultRequestCulture = new RequestCulture("nl-NL");
        // Formatting numbers, dates, etc.
        opts.SupportedCultures = supportedCultures;
        // UI strings that we have localized.
        opts.SupportedUICultures = supportedCultures;
        opts.DefaultRequestCulture = new RequestCulture(culture: "nl-NL", uiCulture: "nl-NL");
    });
    
    Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");
    
  • Setting the culture in Startup.cs Configure class:

    var supportedCultures = new[] { new CultureInfo("nl-NL") };
    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("nl-NL"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
    });
    
    Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");
    
  • Data annotation in viewmodel and normal model, the property first was a DateTime property but that also didn't work:

    [DisplayName("Datum van machtiging")]
    [Required(ErrorMessage = "Het veld '{0}' is verplicht")]
    [DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public string Datum_van_machtiging { get; set; }
    
  • The HTML where it is getting called (if that matters):

    <div class="form-group">
        <label asp-for="Datum_van_machtiging" class="control-label"></label>
        <input asp-for="Datum_van_machtiging" class="form-control" />
        <span asp-validation-for="Datum_van_machtiging" class="text-danger"></span>
    </div>
    
  • Set the right globalization for IIS express as I publish it to IIS. IIS globalization

  • My program.cs (If that matters because I publish to local IIS.)

    public class Program
    {
        public static void Main(string[] args)
        {
           BuildWebHost(args).Run();
        }
    
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls(@"http://0.0.0.0:5000")
                .UseIISIntegration()
                .UseEnvironment("Production")
                .UseStartup<Startup>()
                .Build();
    }
    

EDIT: I am getting this warning too by the way: http://prntscr.com/nxu1d6

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Aids Jung
  • 63
  • 1
  • 7
  • 1
    DateTime is a binary value, it doesn't have any format. The date-related types in SQL Server have no format either. Formats apply *only* when a DateTime gets formatted as a string, or some string gets parsed into a DateTime. You can only *cause* problems by trying to hard-code locales. – Panagiotis Kanavos Jun 05 '19 at 08:07
  • 1
    The big problem is `string Datum_van_machtiging`. Use the *correct* type for dates, ie `DateTime` – Panagiotis Kanavos Jun 05 '19 at 08:09
  • 1
    You probably should state more clearly what you want to achieve and where it goes wrong? – Ilya Chernomordik Jun 05 '19 at 08:11
  • To fix the problem remove **all** attempts at hard-coding the culture and **all** attempts of storing dates as strings, either as object properties or database fields. You can guarantee at least one end user in Netherlands uses German as the first browser language. – Panagiotis Kanavos Jun 05 '19 at 08:17
  • Once you get rid of the strings, the only thing that can cause trouble is the user's input. Just *don't* let users enter open-ended text. Use a date picker input, and extract the value as an ISO string. When posting from Javascript ensure you use `toISOString()`. [HTML 5's date input](https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format) will post an ISO date even though it uses the end user's locale for presentation. jQuery date picker plugins return the displayed text and actual date values through different methods – Panagiotis Kanavos Jun 05 '19 at 08:19

2 Answers2

1

Why are you using string in Datum_van_machtiging field? You can try:

public Datetime Datum_van_machtiging { get; set; }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

You do this in your startup:

Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");

This is probably not what you want to do since it will do that for thread running startup and you probably don't do anything culture specific there. I.e. it won't affect threads running your requests. If you want to lock to one culture only, you can try this instead

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("nl-NL");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("nl-NL");

Maybe I did not quite understand correctly what your problem is as you do not state exactly what goes wrong and where you don't get your date wrong. These setting will affect culture specific operations like number to string conversions and which resource files are read.

If your problem is HTML input (which is not quite clear from your question), then the best thing you can do is to use ISO format from javascript that C# understands well enough. E.g. 2019-06-01. Then you don't need anything additional to do the transformation to specific culture.

I would also ensure validation of this ISO format to be sure it's not possible to send date in a random format that C# may or may not randomly understand depending on a culture.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • That will probably be overriden by the end user's browser language selection. – Panagiotis Kanavos Jun 05 '19 at 08:08
  • Does not this setting have a "higher" priority if it is set? – Ilya Chernomordik Jun 05 '19 at 08:09
  • The OP is storing dates in a string property. That's what causes the problem in the first place – Panagiotis Kanavos Jun 05 '19 at 08:09
  • And assumed that DateTime is broken. It's not. The OP littered the code with hard-coded NL cultures, even though most of Europe uses that date format. That's guaranteed to cause quite a bit of trouble, especially in trilingual Netherlands. You can bet at least one user use German settings, which use dots – Panagiotis Kanavos Jun 05 '19 at 08:13
  • I suspect the OP had trouble with the *HTML input* and assumed the issue was DateTime, not the HTML text or Javascript input. – Panagiotis Kanavos Jun 05 '19 at 08:14
  • if you can't change your client to send ISO (which is probably the best thing to do), you can accept a string and then convert it yourself: `DateTime.ParseExact("dd/MM/yyyy")`. But then you need to be sure it's always in this format from frontend – Ilya Chernomordik Jun 05 '19 at 08:34