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
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')
}
$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.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"
}