Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to datetime in PowerShell

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?

like image 394
Silentbob Avatar asked Aug 02 '16 10:08

Silentbob


People also ask

How do I convert a string to a DateTime in PowerShell?

Use DateTime ParseExact() method or cast to Datetime format to convert string to DateTime.

How do I format a date in PowerShell?

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).

How do I get the current DateTime in PowerShell?

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.


2 Answers

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

like image 196
Chris Dent Avatar answered Sep 22 '22 06:09

Chris Dent


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 
like image 34
Tolga Avatar answered Sep 22 '22 06:09

Tolga