簡體   English   中英

如何將帶時區的 DateTime 轉換為 Unix TimeStamp ? C#

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

這是我運行的代碼:

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();

然后它崩潰了,這是例外:

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.

謝謝!

嘗試轉換為 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