简体   繁体   中英

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 :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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