ParseExact 将字符串转换为日期格式

ParseExact to convert string to date format

我有一个日期列格式如下的 csv 文件。我如何使用 ParseExact 命令转换为日期格式以与当前日期进行比较。

Thu Oct 28 09:40:54 WEST 2021
Sun Mar 20 07:23:44 WET 2022
Sat Oct 30 15:23:02 EDT 2021
Thu Aug 26 11:07:22 SGT 2021
Tue Sep 28 10:00:54 HKT 2021
Fri Jan 07 11:08:45 SAST 2022
$date = "Thu Oct 28 09:40:54 WEST 2021"
[datetime]::ParseExact($date, 'ddd MMM dd HH:mm:ss \W\E\S\T yyyy', [cultureinfo]'en-US')

这有效..但是我如何遍历所有日期字符串并与当前日期进行比较。

正如 评论的那样,您需要解析时区缩写并从中获取 UTC 偏移量,以便将字符串转换为可以比较的日期。
下面通过使用一个开关来做到这一点,但是如果文件中有很多不同的时区,则最好使用查找哈希表。

Import-Csv -Path 'X:\dates.csv' | ForEach-Object {
    # assuming the property is listed under a column header 'Date'
    if ($_.Date -match '(WES?T|EDT|SGT|HKT|SAST) \d{4}$') {
        # either use this switch or create a Hashtable with all UTC offsets
        # for each TimeZone abbreviation you might have in the CSV

        # for demo, I'm using a switch
        $UTCoffset = switch ($matches[1]) {
            'WET'  { 0; break}  # Western Europe Standard Time
            'WEST' { 1; break}  # Western European Summer Time
            'EDT'  {-4; break}  # Eastern Daylight Time
            'EST'  {-5; break}  # Eastern Standard Time
            'SGT'  { 8; break}  # Singapore Time (Standard time)
            'HKT'  { 8; break}  # Hong Kong Time (Standard time)
            'SAST' { 2; break}  # South Africa Standard Time
        }
        # remove the timezone abbreviation from the date string
        $dateToParse = $_.Date -replace "$($matches[1]) "
        # parse the date as UTC ([cultureinfo]'en-US' can be replaced by [cultureinfo]::InvariantCulture)
        $dateUTC = ([datetime]::ParseExact($dateToParse, 'ddd MMM dd HH:mm:ss yyyy', [cultureinfo]'en-US')).AddHours(-$UTCoffset)
        # unfortunately, the above specifies the .Kind property as 'Local', so we must first set this to 'Utc'
        # and then do .ToLocalTime() on it in order to compare with our local reference date
        $dateLocal = ([datetime]::SpecifyKind($dateUTC, 'Utc')).ToLocalTime()

        # do your comparison here against the reference date
        # for demo, just output the converted date
        Write-Host "'$($_.Date)' translates to $dateLocal"
    }
}