Silentbob Silentbob - 2 months ago 26x
Powershell Question

Powershell convert string to datetime

I am using powershell to try and convert a string to a datetime. Should be easy right?

I am getting the string from a csv import and it comes in in the format of

. I have tried multiple ways of getting it into the format I want which is
and I am currently at the following.

$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
$invoice = [datetime]::parseexact($invoice, 'yyyy-MM-dd', $null)

But I get the error:

String was not recognized as a valid DateTime.

Am I missing something?


ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')