简体   繁体   English

C#Unix时间戳到DateTime

[英]C# Unix Timestamp to DateTime

I appreciate that this question has been covered many times over in various forms, but none seem to help with the particular problem that I'm experiencing. 我很欣赏这个问题已经以各种形式被多次讨论,但是似乎没有一个问题可以解决我遇到的特定问题。 I have the following method that I use to convert incoming data to a C# DateTime variable. 我使用以下方法将传入数据转换为C# DateTime变量。 The trouble is, the company sending the data in are claiming that I'm converting it incorrectly because the times are appearing one hour behind in my system. 问题在于,发送数据的公司声称我的数据转换不正确,因为时间在我的系统中出现了一个小时。 I would assume that this is something to do with British Summertime, but is the problem at my end, or at their end, because I thought the method below would be taking account of British Summertime by the fact I'm using ToLocalTime ? 我以为这与英国夏令时有关,但问题到底是在我还是他们的末尾,因为我认为下面的方法会因为我正在使用ToLocalTime而将英国夏令时考虑在内? Any help would be gratefully accepted. 任何帮助将不胜感激。

private DateTime ConvertTimeStamp(double t)
{
    return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
        .AddMilliseconds(t)
        .ToLocalTime();
}

ToLocalTime will adjust the timezone to be whatever the local time is of the computer actually running this method. ToLocalTime会将时区调整为实际运行此方法的计算机的本地时间。 Depending on where it's run from/deployed in the cloud this can give you wildly different results. 根据它在云中运行/部署的位置,这可能会给您带来截然不同的结果。 Timezones can be a huge pain in the butt for this kind of stuff. 时区可能会给这类事情带来极大的痛苦。 It would be ideal if they would send you the UTC unix representation and you could unwrap your DateTime with ToUniversal and from there you can safely convert it back to a timezone of your choosing. 如果他们会向您发送UTC Unix表示形式,并且您可以使用ToUniversal解开DateTime,然后从那里安全地将其转换回您选择的时区,则将是理想的选择。

If they're not sending UTC you need to find out exactly what Timezone that they're expecting and use that specifically instead of ToLocal. 如果他们不发送UTC,则需要确切地找到他们期望的时区,并专门使用它而不是ToLocal。

Well it depends what they are giving you. 好吧,这取决于他们给你的东西。 But assuming they are giving you UTC linux time you could be using this method of .Net 4.6 and convert it to your local time via .ToLocalTime() . 但是假设他们给您UTC linux时间,您可以使用.Net 4.6的这种方法,并通过.ToLocalTime()将其转换为本地时间。 As the other answer suggests, it would be better to make sure to specify a " TimeZoneInfo " instead of using the .ToLocalTime() . 正如另一个答案所建议的那样,最好确保指定一个“ TimeZoneInfo ”,而不要使用.ToLocalTime()

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

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