提问人:Hellagur 提问时间:10/31/2023 最后编辑:HilleHellagur 更新时间:10/31/2023 访问量:47
为什么本地 datetime 与 utc datetime 具有相同的时间戳,无论其 DateTime 或 DateTImeOffset 如何?
Why local datetime has the same timestamp with utc datetime, no matter its DateTime or DateTImeOffset?
问:
我已经检查了这个问题 DateTime local 和 utc 相同,但仍然不知道。
这是我的代码
DateTime localNow = DateTime.Now;
DateTime utcNow = DateTime.UtcNow;
Int64 localTimeStamp = ((DateTimeOffset)localNow).ToUnixTimeSeconds();
Int64 utcTimeStamp = ((DateTimeOffset)utcNow).ToUnixTimeSeconds();
Console.WriteLine("With Datetime");
Console.WriteLine("Current time: " + localNow.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + localTimeStamp);
Console.WriteLine("Current Utc time: " + utcNow.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + utcTimeStamp);
DateTimeOffset localNowOff = DateTimeOffset.Now;
DateTimeOffset utcNowOff = DateTimeOffset.UtcNow;
Int64 localOffTimeStamp = localNowOff.ToUnixTimeSeconds();
Int64 utcOffTimeStamp = utcNowOff.ToUnixTimeSeconds();
Console.WriteLine("With DatetimeOffset");
Console.WriteLine("Current time: " + localNowOff.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + localOffTimeStamp);
Console.WriteLine("Current Utc time: " + utcNowOff.ToString("yyyy/MM/dd HH:mm:ss") + " timestamp: " + utcOffTimeStamp);
这是输出:
With Datetime
Current time: 2023/10/31 23:11:33 timestamp: 1698765093
Current Utc time: 2023/10/31 15:11:33 timestamp: 1698765093
With DatetimeOffset
Current time: 2023/10/31 23:11:33 timestamp: 1698765093
Current Utc time: 2023/10/31 15:11:33 timestamp: 1698765093
我不相信本地 ant utc 之间的时间戳结果应该相同,但它确实发生了。
但是,当我尝试从时间戳获取本地日期时间时,结果是 utc datetime,如下所示:
DateTime localNow = DateTime.Now;
Int64 localTimeStamp = ((DateTimeOffset)localNow).ToUnixTimeSeconds();
DateTime localDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
localDateTime = localDateTime.AddSeconds(localTimeStamp).ToLocalTime();
Console.WriteLine("Convert local timestamp to datetime: " + localDateTime.ToString("yyyy/MM/dd HH:mm:ss"));
那么我做错了什么,获取有关本地时间和UTC时间的时间戳并转换回日期时间的正确方法是什么?
答:
0赞
Hille
10/31/2023
#1
没有本地 unix 时间戳,因为纪元 unix 时间戳始终为 UTC+0。
如果要将时间戳转换为本地时间戳,请执行如下操作:
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(1698766249);
DateTime localDt = dt.LocalDateTime;
评论
0赞
Hellagur
11/8/2023
现在我明白了,谢谢你的帮助!
0赞
Hille
11/8/2023
@Hellagur 如果我的答案击中了你的靶心,请随时竖起大拇指或放弃梦寐以求的复选标记!很乐意为您提供帮助。干杯!
评论
DateTimeOffset.Now
DateTimeOffset.UtcNow