0

I have a date as string in the the following form:

July 27th, 2016
December 3rd, 2014
August 1st, 1998
March 2nd, 1979

How do I convert the date to the following using PowerShell

2016-07-27
2014-12-03
1998-08-01
1979-03-02

2 Answers 2

2

I would opt for ParseExact() with some regex to remove all th's, rd's, st's. Than you just have to use correct format in ToString()

EDIT updating the code based on @JosefZ suggestion.

foreach ($date in @(
    'July 27th, 2016'
    'December 3rd, 2014'
    'August 1st, 1998'
    'March 2nd, 1979'
)) {
    $clean = $date -replace '(st|nd|rd|th),'
    $dateObject = [datetime]::ParseExact($clean, 'MMMM d yyyy', [System.Globalization.CultureInfo]::InvariantCulture)
    # Apparently, this works too ...    
    $dateObject = [datetime]$clean  
    $dateObject.ToString('yyyy-MM-dd')
}
Sign up to request clarification or add additional context in comments.

1 Comment

$dateObject = [datetime]$clean should suffice. For my locale, ParseExact raises Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime.". Replace 3rd argument $null with [System.Globalization.CultureInfo]::InvariantCulture.
0

In addition to the method shown by @Andrii-Matus, @BartekB, the following is another way to achieve the same thing.

$date_str = @(
    'July 27th, 2016'
    'December 3rd, 2014'
    'August 1st, 1998'
    'March 2nd, 1979'
)

foreach ($date in $date_str){
    $newformat = $date -replace '(st|nd|rd|th),'
    get-date $newformat -UFormat "%Y-%m-%d"
}

Comments

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.