Parsing and reformatting date string using PowerShell

2

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!

Bjørn H. Sandvik

Posted 2017-10-13T10:07:38.610

Reputation: 199

1Assuming you already know how to import the csv-file in powershell this should point you into the right direction: Get-Date 8-10-2017 -Format "MM.dd.yyyy" – whatever – 2017-10-13T10:28:00.333

That works like a charm, except it misinterprets the positioning of original day and month. 8-10 means Oct 8, not Aug 10 which is what the cmdlet spits out.. – Bjørn H. Sandvik – 2017-10-13T11:02:55.533

1In that case you will have to tell powershell which culturesetting to use: $Culture = New-Object system.globalization.cultureinfo 'en-us'; Get-Date ([datetime]::parse("8-10-2017",$Culture)) -Format dd.MM.yyyy – whatever – 2017-10-13T11:12:51.697

I want to like PowerShell so very bad.. Thank you for a complete and excellent solution, whatever! – Bjørn H. Sandvik – 2017-10-13T11:18:40.857

Answers

2

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.

Jeff Zeitlin

Posted 2017-10-13T10:07:38.610

Reputation: 2 918