Change default timezone in ASP.NET Core 2.2 on Docker for 24h time format
Asked Answered
A

2

11

I want to use German date formatting as default for my ASP.NET Core 2.2 application. On my Win10 machine with German language/layout it works, so I assumed that the timezone has to be set in my Dockerfile. According to the Alpine wiki, I did this:

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-alpine3.9 AS build-env
ENV TZ=Europe/Berlin
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore

RUN apk add tzdata \
        && cp /usr/share/zoneinfo/${TZ} /etc/localtime \
        && echo "${TZ}" > /etc/timezone

COPY . ./
RUN dotnet publish -c Production -o dist
ENTRYPOINT ["dotnet", "./dist/MyApp.dll"]

According to the date command, this worked:

/app # date
Sun Apr  7 13:50:42 CEST 2019
/app # date -u
Sun Apr  7 11:50:40 UTC 2019

But having a DateTime object in my Model from the Database

<td>@article.PublishedTime.ToString("g")</td>

I get 4/7/19 12:16 AM where my German Win10 machine shows 07.04.2019 00:16. Why isn't this working? Since ASP.NET Core uses the system timezone, it should now use the 24h time format as set in linux.

Apophthegm answered 7/4, 2019 at 11:56 Comment(0)
A
18

Found out that we need to set the language, since this is used for the formatting:

ENV TZ=Europe/Berlin
ENV LANG de_DE.UTF-8
ENV LANGUAGE ${LANG}
ENV LC_ALL ${LANG}

This works and produces German 24h DateTime formattings.

I agree that in most cases this should be controlled by the application, which use different formattings on e.g. user specified settings. Since this is a simple application only for me, it's the easiest way to set the server settings to my localisation. Passing a culture info from any kind of settings would produce overhead without advantage.

But as I said this is only suiteable for my case. In a productive environment you may want to specify the colture and allow different cultures for international users.

Apophthegm answered 7/4, 2019 at 12:36 Comment(3)
thx this helped a lot for our .NET Core app which we converted to docker/k8s. Wondered why the date/time was "not" correct. If you see the solution it is so obvious :DCharactery
If you ask me, this is invalid. There are missing = between the variables and the values.Threadfin
Still working for net7 / K8sFellowman
H
2

The formatting of the "general" date/time is governed by the machine or process locale not the timezone. It should never be relied on to produce a specific format. Either set the CultureInfo, or specify the exact format you want:

Publishedtime.ToString("g",CultureInfo.CreateSpecificCulture("de-DE"))
Publishedtime.ToString("dd.MM.yyyy HH:mm"))
Hansel answered 7/4, 2019 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.