Search code examples
c#dockerdatetime.net-coretimezone

.net core 6 on docker DateTime.TryParseExact is not working for en-GB timezone


I'm running my app with the dockerfile below the date conversion is not working inside of container, but it works on windows and ubuntu, here you go an exemple of the code that is failling:

var culture = new CultureInfo("en-GB");

Console.WriteLine(DateTime.TryParseExact("SEP24", "MMMyy",  culture, DateTimeStyles.None, out var valueDate));
Console.WriteLine(valueDate);

it return true on others system but inside of container it's returning false.

FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build-env
WORKDIR /App
# Copy everything
COPY . ./

ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
ENV DOTNET_RUNNING_IN_CONTAINER=true

RUN apk add --no-cache tzdata
RUN apk add --no-cache  icu-data-full icu-libs

# just for exemple
RUN dotnet run

RUN dotnet restore
# Build and publish a release
RUN dotnet publish -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /App

RUN apt-get update -y && apt-get install -y tzdata

COPY --from=build-env /App/out .
ENTRYPOINT ["dotnet", "DotNet.Docker.dll"]

I have added tzdata, the timezone GB is present in the container, but it not solve the problem.


Solution

  • Are you using the System.Globalization Nuget package?

    I tried reproducing your issue and I can't. I created the following self-contained Dockerfile (which doesn't install tzdata) which creates a console app and adds your code.

    When I build and run it with

    docker build -t test .
    docker run --rm test
    

    it prints

    True
    09/01/2024 00:00:00
    

    My Dockerfile:

    FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build-env
    WORKDIR /App
    
    # Create a console application and add System.Globalization Nuget package
    RUN dotnet new console -n DotNet.Docker -o .
    RUN dotnet add package System.Globalization --version 4.3.0
    
    # Overwrite Program.cs with our own code
    RUN cat <<EOF > Program.cs
    using System.Globalization;
    var culture = new CultureInfo("en-GB");
    Console.WriteLine(DateTime.TryParseExact("SEP24", "MMMyy",  culture, DateTimeStyles.None, out var valueDate));
    Console.WriteLine(valueDate);
    EOF
    
    # Restore and build
    RUN dotnet restore
    RUN dotnet publish -c Release -o out
    
    # Build runtime image
    FROM mcr.microsoft.com/dotnet/aspnet:6.0
    WORKDIR /App
    
    COPY --from=build-env /App/out .
    ENTRYPOINT ["dotnet", "DotNet.Docker.dll"]