[英]Powershell string to unix time with correct timezone
我正在收集時間戳值並嘗試將其轉換為 Unix 格式。
為此,我使用 ParseExact 方法,如下所示:
$FILETIME = "20220709101112"
$EPOCHTIME = [datetime]::ParseExact($FILETIME,"yyyyMMddHHmmss",$null) | Get-Date -UFormat "%s"
echo $EPOCHTIME
1657361472
Get-Date 將時間戳正確地轉換為 Unix 格式,但是有一個問題。 返回值使用本地時區 (UTC-3),而不是 UTC-0。
因此,在另一個系統中,該值可能會以錯誤的時區顯示。
我試圖增加 3 個小時,但它卻附加了數字。
$EPOCHTIME = $EPOCHTIME + 10800
echo $EPOCHTIME
165736147210800
如何正確轉換該時間戳?
好的,這是一種方法(借鑒自https://stackoverflow.com/a/246529/3156906 )。
關鍵是找到$FILETIME
字符串所在時區的 TimeZoneInfo,並在轉換為 Unix 紀元時間戳之前使用它將本地時間轉換為 UTC。
# datetime string that is local to UTC-3,
# (equivalent to "2022-07-09 13:11:12 UTC")
$FILETIME = "20220709101112";
# because there's no timezone component in the custom
# format string (e.g. "z" or "zz") this gets converted
# to a datetime with "Kind = DateTimeKind.Unspecified"
# (see https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-6.0#system-datetime-parseexact(system-string-system-string-system-iformatprovider))
$TIMESTAMP = [datetime]::ParseExact($FILETIME, "yyyyMMddHHmmss", $null);
# DateTime : 09 July 2022 10:11:12
# Kind : Unspecified
# get a reference to the timezone the original date
# string is stored local to. I guessed this by looking
# at the results of "[TimeZoneInfo]::GetSystemTimeZones()"
# and taking a timezone with -3:00 from UTC and no daylight savings
# but maybe there's a better match for your source data
$tz = [TimeZoneInfo]::FindSystemTimeZoneById("SA Eastern Standard Time");
# Id : SA Eastern Standard Time
# DisplayName : (UTC-03:00) Cayenne, Fortaleza
# StandardName : SA Eastern Standard Time
# DaylightName : SA Eastern Summer Time
# BaseUtcOffset : -03:00:00
# SupportsDaylightSavingTime : False
# this is the magic bit - treat $TIMESTAMP as a local time in
# timezone $tz, and convert it to UTC using the BaseUtcOffset
# and daylight saving rules for $tz
$UTCTIME = [TimeZoneInfo]::ConvertTimeToUtc($TIMESTAMP, $tz);
# DateTime : 09 July 2022 13:11:12
# Kind : Utc
# now convert it to a unix epoch timestamp
$EPOCHTIME = $UTCTIME | Get-Date -UFormat "%s";
# 1657372272
獎金回合
您會得到 Unix 紀元時間戳 1657361472,因為您運行腳本的計算機上的當前時區是 UTC,它與字符串所在的時區相差 3 小時。
如果 s 不代表特定時區的時間並且解析操作成功,則返回的 DateTime 值的 Kind 屬性為 DateTimeKind.Unspecified。 如果 s 確實表示特定時區中的時間並且格式允許存在時區信息(例如,如果格式等於“o”、“r”或“u”標准格式說明符,或者如果它包含“z”、“zz”或“zzz”自定義格式說明符),返回的 DateTime 值的 Kind 屬性是 DateTimeKind.Local。
這個問題已經在這篇文章中得到了回答:
本質上,它取決於您使用的 PowerShell 版本。 如果是 Powershell 7.1+,那么你可以這樣做:
Get-Date -AsUTC -UFormat "%s"
否則,如果是低版本,則需要使用
Get-Date ([datetime]::UtcNow) -UFormat "%s"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.