Trouble with converting to Datetime object
Solution 1:
You can use the the ParseExact()
method provided by the [datetime]
class for this:
[datetime]::ParseExact('Fri Jan 14 20:58:09','ddd MMM dd HH:mm:ss',$null)
# returns a - datetime - object of:
# Friday, January 14, 2022 8:58:09 PM
- dd - for the day.
- MM - for the month.
- HH - for the hour - Capitalized for the 24 hour time format.
- mm - for the minutes.
- ss - for the seconds.
Edit: as suggested by mklement0, we can use [cultureinfo]::InvariantCulture
to make the parsing specific to an English date time format. Also, changing dd to d as a more robust solution for days without 2 digits; which should cover both singular, and double digit days.
Seeing $timestamps
is an array of strings, you can use a loop (of your choice - in this case the Foreach-Object
cmdlet) to iterate through each string parsing the text to return a datetime
object:
$timestamps | ForEach-Object {
$culture = [cultureinfo]::InvariantCulture
$format = 'ddd MMM d HH:mm:ss'
$date = [datetime]::ParseExact($_,$format,$culture,'AssumeUniversal, AdjustToUniversal')
[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date, 'Eastern Standard Time')
}
- Using
'AssumeUniversal, AdjustToUniversal'
ensures a UTC output.
Assuming from your comment that you'd like to do a conversion to Eastern Time, passing the newly created datetime object to [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId()
with an argument of the desired time zone, you can get your result in the new time zone.
When using $null
, the CultureInfo object that corresponds to the current culture is used.