如果您可以假设时区缩写后缀(例如,PST)总是指本地时区:
您可以简单地去掉后缀并直接转换为[datetime]:
# Sample input.
$dateStr = 'Mon, 02 Nov 2020 06:39:24 PST'
# Strip a 3-letter suffix preceded by a space, if present.
# If there is no such suffix, the input string is used as-is.
# Note: Resulting [datetime] instance has .Kind value Unspecified.
[datetime] ($dateStr -creplace '^(.+) [A-Z]{3}$', '$1')
请注意,结果将以本地时间表示,但生成的[datetime] 实例将具有.Kind 值Unspecified 而不是Local,当您调用.ToLocalTime() 时,此类实例的行为类似于UTC他们。
为确保您获得明确表示本地时间的Local 实例(尽管相对于本地机器的时区),请使用[datetimeoffset] 进行转换并使用生成的实例的.LocalDateTime 属性:
$dateStr = 'Mon, 02 Nov 2020 06:39:24 PST'
# Resulting [datetime] instance has .Kind value Local.
([datetimeoffset] ($dateStr -creplace '^(.+) [A-Z]{3}$', '$1')).LocalDateTime
如果可行,使用[datetimeoffset] (System.DateTimeOffset) 而不是[datetime] (System.DateTime)通常更可取,因为[datetimeoffset] 实例明确代表一个具体的、独立的时间点。
如果时区缩写后缀可以代表任意时区:
不幸的是,[System.TimeZoneInfo]::GetSystemTimeZones()) 返回的预定义时区信息对象确实不包含诸如PST 之类的缩写,但是,这是有充分理由的:此类缩写没有全球标准,所以PST 可以指代世界不同地区的不同时区。
这意味着您必须创建自己的这些后缀到它们所代表的 UTC 偏移量的映射,例如 -08:00 代表 PST,如果解释为美国 Pacific (Standard) Time时区:
# Sample input.
$dateStr = 'Mon, 02 Nov 2020 06:39:24 PST'
# Map time-zone abbreviations such as 'PST' to their UTC offset.
# IMPORTANT: Be sure to define mappings for all suffixes you may encounter
# in your input.
$tzAbbrevToUtcOffsetSuffix = @{
'PST' = '-08:00'
}
if ($dateStr -cmatch '^(.+) ([A-Z]{3})$') { # Time-zone suffix present.
# Map the suffix to its UTC offset.
$utcOffset = $tzAbbrevToUtcOffsetSuffix[$Matches.2]
if (-not $utcOffset) { Throw "No UTC offset defined for timze-zone abbreviation: $($Matches.2)" }
# Replace the suffix with its UTC offset in the input string.
$dateStr = $Matches.1 + ' ' + $utcOffset
# Tell ::ParseExact() below to expect a UTC offset.
$formatSuffix = ' K'
} else { # No time-zone suffix.
# Assume it is a local date without time-zone suffix.
$formatSuffix = ''
}
# Use [datetimeoffset] for parsing, so we can create a [datetime] instance
# with .Kind 'Local'.
[datetimeoffset]::ParseExact(
$dateStr,
('ddd, dd MMM yyyy HH:mm:ss' + $formatSuffix),
[cultureinfo]::InvariantCulture
).LocalDateTime