Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date format from DD.MM.YYYY to YYYY-MM-DD

I have folders on the disk in the german format: "01.05.2019", which I want to convert into the english format: "2019-05-01".

I am using PowerShell. Is there a fancy function for doing this? Or should I get all substrings and reorder them?

Currently I only collect the strings:

$OrgDir = "P:\Fotos\Import"
$folders = Get-ChildItem $($OrgDir) -Directory 
foreach ($dir in $folders) {
    Write-Host "folder: " $dir
}
like image 625
Matthias Pospiech Avatar asked Jan 23 '26 22:01

Matthias Pospiech


1 Answers

Use [DateTime]::ParseExact() to avoid the date parser mixing up the month and day:

$OrgDir = "P:\Fotos\Import"
$folders = Get-ChildItem $OrgDir -Directory
foreach ($dir in $folders) {
    Write-Host "folder: $([DateTime]::ParseExact($dir.Name, "dd.MM.yyyy", $null).ToString("yyyy-MM-dd"))"
}

The above prints out the converted names. To efficiently rename the files however, I recommend this:

Get-ChildItem $OrgDir -Directory | 
    ForEach-Object {
        $_ | Rename-Item -NewName (
            [DateTime]::ParseExact($_.Name, "dd.MM.yyyy", $null).ToString("yyyy-MM-dd")
        )
    }

This line of PowerShell renames all directories at $OrgDir to the new date format, given that all directories in the folder are named this way.

Reference


UPDATE:

As @Matt Johnson pointed out, $null uses your system default culture for ParseExact(string, format, culture) (as well as ToString(format, culture)). This may or may not cause problems based on what culture setting your system currently has.

To ensure these settings do not interfere with this function, use [System.Globalization.CultureInfo]::InvariantCulture for the culture parameters in both ParseExact() and ToString().

like image 137
spicy.dll Avatar answered Jan 25 '26 16:01

spicy.dll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!