在 .net core 中设置全球时区

sha*_*haf 7 c# timezone datetime .net-core asp.net-core

在 .Net Core 2 中 -

有没有办法全局设置应用程序的时区,以便每当我请求时,DateTime.Now我都会获得我想要的时区的当前时间(比如 GMT+3),而不是托管应用程序的服务器的时间?

我认为有一个配置的好地方是 Startup.cs 文件,但我的搜索查询让我无处可去。

小智 6

您可以为此使用 TimeZoneInfo

DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Eastern Standard Time");
Run Code Online (Sandbox Code Playgroud)

替换为所需的时区。

  • 小心跨平台问题:https://devblogs.microsoft.com/dotnet/cross-platform-time-zones-with-net-core/ (5认同)

Mat*_*int 5

不。

DateTime.Now始终返回系统本地时区的时间。