我正在收集时间戳值,并试图将其转换为Unix格式。
为此,我使用了ParseExact方法,如下所示:
$FILETIME = "20220709101112"
$EPOCHTIME = [datetime]::ParseExact($FILETIME,"yyyyMMddHHmmss",$null) | Get-Date -UFormat "%s"
echo $EPOCHTIME
1657361472Get正确地将时间戳转换为Unix格式,但有一个问题。返回的值使用本地时区(UTC-3),而不是UTC-0。
因此,在另一个系统中,该值可能会以错误的时区显示。
我试着增加3个小时,但它却附加了这个数字。
$EPOCHTIME = $EPOCHTIME + 10800
echo $EPOCHTIME
165736147210800如何正确地转换时间戳?
发布于 2022-07-11 22:51:58
好的,这里有一种方法(从https://stackoverflow.com/a/246529/3156906借来)。
关键是为TimeZoneInfo字符串的本地时区查找$FILETIME,并在转换为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://learn.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小时。
关于 DateTime.ParseExact法的说明
如果s不表示特定时区中的时间,并且解析操作成功,则返回的DateTime值的种类属性为DateTimeKind.Unspecified。如果s确实表示特定时区和格式中的时间,则允许时区信息存在(例如,如果格式等于"o“、"r”或"u“标准格式说明符,或者它包含"z”、"zz“或"zzz”自定义格式说明符),则返回的DateTime值的类型属性为DateTimeKind.Local。
发布于 2022-07-11 14:36:06
这一问题在这篇文章中得到了回答:
本质上,这取决于您正在使用的PowerShell版本。如果是Powershell 7.1+,那么您可以:
Get-Date -AsUTC -UFormat "%s"否则,如果它是一个较低的版本,您需要使用
Get-Date ([datetime]::UtcNow) -UFormat "%s"https://stackoverflow.com/questions/72940106
复制相似问题