Home > Enterprise >  ParseExact to convert string to date format
ParseExact to convert string to date format

Time:04-07

I have a csv file with date column format as below. How can i use ParseExact command to convert to date format to compare with current date.

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')

this works.. but how do i loop through all the date string and compare with current date.

CodePudding user response:

As Jeroen Mostert commented, you need to parse out the TimeZone abbreviations and get the UTC offset from that so you can convert the strings to dates you can compare.
Below does this by using a switch, but if you have lots of different timezones in the file, using a lookup Hashtable would be preferable.

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"
    }
}
  • Related