unknown Javi
unknown Javi

Reputation: 41

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!

Upvotes: 1

Views: 2579

Answers (1)

mm8
mm8

Reputation: 169200

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;

Upvotes: 2

Related Questions