ASP.NET Core 7 MVC Web Application default date formatting

30 Views Asked by At

I have a web application which is working fine on my local machine in development mode. The application is being deployed to a Docker Container in AWS. All appears to be fine, until I noticed that the dates were displaying incorrect whenever the could be incorrect.

I need the dates to be read by default as UK dates, which is fine on local machine, but in AWS they are defaulting to US style dates:

I use DateTime.Parse(dateString) to get the dates, anyone know how to change the default from US to UK, without having to revisit every line of code which converts the date and reformatting it? (lots of dates in application)

Examples:

31/01/2022 - this date will be read as a UK date 01/02/2022 - this will get the month and day mixed up, so instead of 1st Feb 2022, it will be converted to 2nd Jan 2022

I have tried setting the docker timezone to GMT, but this still doesnt prevent the dates being read incorrectly.

RUN ln -sf /usr/share/zoneinfo/posix/Europe/London /etc/localtime

1

There are 1 best solutions below

0
Andie On

I managed to make this work.. I created a static class with one method

public static class ApplicationCulture
{
    public static void SetCulture()
    {
        CultureInfo ci = new CultureInfo("en-GB");
        ci.DateTimeFormat.FullDateTimePattern = "dd/MM/yyyy HH:mm:ss";
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }
    
}

and from the constructor of each controller I called

ApplicationCulture.SetCulture();

So now the culture is set to the current thread and the date is parsed correctly. I based my solution on this thread how to set default culture info for entire c# application

Thanks for the suggestions, I hope this helps someone in a similar situation