Home > Back-end >  Converting Date string to datetime in powershell
Converting Date string to datetime in powershell

Time:11-12

I'm having trouble figuring the cleanest way to convert a date from one format to the other.

The dates are formatted "Jul 29th, 2021" and I cant change this in the source as its a system output. When I try to convert to datetime it isn't valid.

if anyone has any idea id appreciate it. An example of one of the things i tried is below

    $date = "Jul 29th, 2021"
    $testConversion = [datetime]$date
    $testConversion

CodePudding user response:

Because you can have strings like th, st, nd or rd in there, always followed by a comma, the best thing to do is to use a regex -replace on these first and next use [datetime]::PareseExact().

To demonstrate:

$dates = 'Jul 29th, 2021', 'Aug 1st, 2021', 'Sep 2nd, 2021', 'Oct 3rd, 2021'

foreach ($date in $dates) {
    [datetime]::ParseExact(($date -replace '((th|st|nd|rd),)?'), 'MMM d yyyy', [cultureinfo]::InvariantCulture)
}

If your culture (locale) is already set to en-US, you can set the third parameter to $null

  • Related