简体   繁体   English

如何将带时区的 DateTime 转换为 Unix TimeStamp ? C#

[英]How I can convert a DateTime with timezone to a Unix TimeStamp ? C#

This is the code I got running:这是我运行的代码:

string dateStart = "2020-03-03T20:12:15+00:00"
DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", null);
long unixStart = ((DateTimeOffset)Start).ToUnixTimeSeconds();

Then it crash, this is the exception:然后它崩溃了,这是例外:

Excepción producida: 'System.ArgumentOutOfRangeException' en System.Private.CoreLib.dll
Excepción no controlada del tipo 'System.ArgumentOutOfRangeException' en System.Private.CoreLib.dll
The UTC time represented when the offset is applied must be between year 0 and 10,000.

Thanks!谢谢!

Try to convert to UTC and subtract DateTime.UnixEpoch :尝试转换为 UTC 并减去DateTime.UnixEpoch

string dateStart = "2020-03-03T20:12:15+00:00";
DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture);

long unixStart = (long)Start
    .ToUniversalTime()
    .Subtract(DateTime.UnixEpoch)
    .TotalSeconds;

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

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