Shell – Parsing and reformatting date string using PowerShell

parsingpowershell

Given a CSV-file containing the following line:

HEAD;1;49999;8-10-2017;;;

.. I need to reformat the date given as d-m-yyyy into fixed length dd.mm.yyyy and/or yyyy-mm-dd (fixed, naturally implying double digit day and month)

While I see much of the cleverness behind PowerShell, I find it rather unwieldy. Any help is greatly appreciated!

Best Answer

This was essentially the problem addressed by the Idera PowerTip of the Day for October 12, 2017. The solution presented was to use the ParseExact method of the DateTime .NET class. Assuming that you've extracted the date from the CSV and stored it in the variable $ActionDateString, you would then convert it to a DateTime object:

$DT = [DateTime]::ParseExact($ActionDateString, "dd-MM-yyyy", $null)

and then you can use the DateTime object $DT as you please.

Related Question