iceman
iceman

Reputation: 506

Trouble with converting to Datetime object

I have the below data which is an object type variable named $timestamps

Sat Jan 15 16:21:24
Sat Jan 15 01:31:22
Fri Jan 14 20:58:09
Fri Jan 14 20:51:02

enter image description here

I'm having trouble converting it to Datetime object because of the weird date format. How would you handle this?

I would like it as a datetime object because I plan to convert from current (UTC) to EST.

TIA

Upvotes: 2

Views: 441

Answers (2)

Abraham Zinala
Abraham Zinala

Reputation: 4694

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.

Upvotes: 6

Bob M
Bob M

Reputation: 932

The DateTime.ParseExact() method is probably what you're looking for.

PS C:\TEMP>$timestamp = 'Sat Jan 15 16:21:24'
PS C:\TEMP>$format    = 'ddd MMM dd HH:mm:ss'
PS C:\TEMP>[datetime]::ParseExact($timestamp, $format, $null)

Saturday, January 15, 2022 04:21:24 PM


PS C:\TEMP>

Upvotes: 1

Related Questions