2

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
0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Hi Thanks for the swift response. So to add this into a larger picture. I have a switch comparison in a for each loop doing some fun stuff with html in powershell 7. It pulls it from a table on a site as a string. I then need to convert that to UK format. Using your script to convert to yankee doodle first just to test reports an error. Exception calling "ParseExact" with "3" argument(s): "String 'Apr 6 2021' was not recognized as a valid DateTime." I altered it to the below $date = [datetime]::ParseExact(($td -replace '(th|st|nd|rd),'), 'MMM dd yyyy', [cultureinfo]'en-US')
@DrJekyll_XYZ Could work, but without seeing that 'whole picture' it is hard to see what you mean here.. The question was on how to turn a formatted date string into a real DateTime object. What you do with that afterwards is of no concern.
Sorry im not used to trying to put things in code blocks on this site so i hit enter by accident
Apr 6 2021 does not contain ordinal abbreviations as the example in your question had.. Anyway, I have changed the regex for that and added [cultureinfo]::InvariantCulture
You know what pal, that's my bad. when i typed it in i added a d into the format. Changing it to invariant culture worked great. Thank you so much for your help there.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.