I am using PowerShell to try and convert a string to a datetime. It should be easy, right?
I am getting the string from a CSV import, and it comes in the format of Jul-16
. I have tried multiple ways of getting it into the format I want which is yyyy-MM-dd
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?
Use DateTime ParseExact() method or cast to Datetime format to convert string to DateTime.
Starting in PowerShell 5.0, you can use the following additional formats as values for the Format parameter. FileDate. A file or path-friendly representation of the current date in local time. The format is yyyyMMdd (case-sensitive, using a 4-digit year, 2-digit month, and 2-digit day).
The Get-Date cmdlet in PowerShell displays the current date and time on the PowerShell console. This cmdlet gets a DateTime object. We can also use the Get-Date to generate and send the date and time character string to the other cmdlets or programs.
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')
Chris
You can simply cast strings to DateTime:
[DateTime]"2020-7-16"
or
[DateTime]"Jul-16"
or
$myDate = [DateTime]"Jul-16";
And you can format the resulting DateTime variable by doing something like this:
'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
or
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
or
$myDate = [DateTime]"Jul-16"; '{0:yyyy-MM-dd}' -f $myDate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With