linux和windows执行日期计算的区别

问题描述 投票:0回答:2

Linux 和 Windows 执行日期计算的方式有重大区别吗?我有一个正在工作的应用程序,它将 DateTime 从任何本地时区转换为 UTC 以存储在数据库中。当我在本地 Windows 开发机器上进行测试时,它执行此操作没有任何问题,但是,在任何更高的环境(即 Linux)中,它似乎应用了两次时区转换。例如,从日期时间“12/5/2022 08:00 AM”开始,我位于亚利桑那州时区,因此 UTC 时间为“12/05/2022 15:00”,但我不是该值,而是看到值“12/6/2022 02:00”被放入数据库中。 以前有人遇到过这种情况吗?如果是的话,你是怎么处理的?


            DateTime currentDate = DateTime.Now;
            Console.WriteLine("The Current Datetime is: " +currentDate.ToString());

            currentDate = DateTime.SpecifyKind(currentDate, DateTimeKind.Unspecified);
            Console.WriteLine("Unspecified kind datetime is: " + currentDate.ToString());

            currentDate = TimeZoneInfo.ConvertTimeToUtc(currentDate, TimeZoneInfo.Local);
            Console.WriteLine("UTC time zone datetime is: " + currentDate.ToString());
            Console.ReadKey();

以上是我正在执行的相关日期计算。我正在使用.net core 3.1

.net-core
2个回答
1
投票

我无法重现任何问题,我也没想到会重现。 Windows 和 Linux 之间的日期计算没有区别。

being put in the database
这可能就是问题所在 - 尝试将本地时间存储在与服务器具有不同“本地”偏移量的数据库中。

问题的代码也不转换时区,它只更改

DateTime.DateTimeKind
属性。在所有情况下,日期时间值保持不变..

调用

TimeZoneInfo.ConvertTimeToUtc(currentDate, TimeZoneInfo.Local)
Unspecified
时间更改为
Local
,而不是
UTC
。即使参数是
TimeZoneInfo.Utc
,也没关系,因为
Unspecified
一开始就没有偏移量。

以下程序确实转换并打印为 UTC。

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
Console.WriteLine("{0} at {1}", Environment.OSVersion,offset);
Console.WriteLine();

DateTime currentDate = DateTime.Now;
DateTime currentUtc=DateTime.UtcNow;

Console.WriteLine("The Current Datetime is: " +currentDate.ToString());
currentDate = DateTime.SpecifyKind(currentDate, DateTimeKind.Unspecified);
Console.WriteLine("Unspecified kind datetime is: " + currentDate.ToString());
currentDate = TimeZoneInfo.ConvertTimeToUtc(currentDate, TimeZoneInfo.Local);
Console.WriteLine("Not-UTC time zone datetime is: " + currentDate.ToString());

Console.WriteLine();
Console.WriteLine("Actual UTC datetime is: {0}", currentUtc);
Console.WriteLine("Current converted to  UTC datetime: {0}", currentDate.ToUniversalTime());

Console.ReadKey();

在 Ubuntu 中运行时,它会打印预期时间:

Unix 5.15.74.2 at 02:00:00

The Current Datetime is: 12/06/2022 10:15:36
Unspecified kind datetime is: 12/06/2022 10:15:36
Not-UTC time zone datetime is: 12/06/2022 08:15:36

Actual UTC datetime is: 12/06/2022 08:15:36
Current converted to  UTC datetime: 12/06/2022 08:15:36

DateTime.UtcNow
返回
08:15:36
而不是当地时间
10:15:36
。使用
currentDate
ToUniversalTime
转换为 UTC 也会转换
currentDate
中存储的本地时间。


0
投票

问题是我们在一个地方将日期作为 DateTime 类型发送。当您执行此操作时,UI 将自动更改时间以匹配服务器上的时区。这就是为什么该问题无法在本地重现,只有部署后才会出现。

© www.soinside.com 2019 - 2024. All rights reserved.