简体   繁体   English

C#从和返回到Unix时间戳

[英]C# Convert from and back to Unix timestamp

I have following unit test which fails我有以下单元测试失败

[Fact]
public void Convert_to_and_from_unix_timestamp()
{
    // Arrange
    var timestamp = 1636579063;
    var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;

    // Act
    var unixTimeSeconds = ((DateTimeOffset)date).ToUnixTimeSeconds();

    // Assert
    Assert.Equal(expected: timestamp, actual: unixTimeSeconds);

    // result
    // Expected: 1636579063 // 10/11/2021 21:17:43
    // Actual: 1636575463 // 10/11/2021 20:17:43
}

The new (actual) Unix timestamp is minus one hour.新的(实际)Unix 时间戳是负一小时。 My machine timezone is UTC+1.我的机器时区是 UTC+1。 Does it mean, that DateTimeOffset is automatically setting up my timezone (UTC+1) into the datetime and when converting back into the timestamp the DateTimeOffset is removing the UTC+1 so there is one hour decrease?这是否意味着 DateTimeOffset 会自动将我的时区 (UTC+1) 设置为日期时间,并且在转换回时间戳时 DateTimeOffset 正在删除 UTC+1,因此减少了一个小时? How can I manage timezone in both ways?如何以两种方式管理时区?

The problem is in .DateTime fragment in the line问题出在.DateTime片段中

    var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;

According to reference source根据参考来源

private DateTime ClockDateTime {
  get {
    // Here we lose Timezone (Offset) - it just added to m_dateTime
    // Kind is Unspecified, that's why we can restore the fact
    // Offset == 0 and we actually have UTC datetime    
    return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
  }
}
 
public DateTime DateTime {
  get {
    return ClockDateTime;
  }
}

.Net creates for .DateTime property a new DateTime instance with Kind == DateTimeKind.Unspecified , so you lose timezone (now Offset from DateTimeOffset is just added to DateTime ). .Net 为.DateTime属性创建一个新的DateTime实例,其中Kind == DateTimeKind.Unspecified ,因此您会丢失时区(现在DateTimeOffset Offset量刚刚添加DateTime )。

In order to correct the test put .UtcDateTime instead of .DateTime :为了更正测试,请使用.UtcDateTime而不是.DateTime

    var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM