Convert string to date and time in PowerShell

I use PowerShell to try to convert a string to a date and time. That should be easy, right?

I get the string from CSV import and it comes in format from Jul-16. I tried several ways to get it in the format I want, this yyyy-MM-ddand currently I am in the following.

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

But I get the error:

The string was not recognized as a valid DateTime.

Did I miss something?

+14
source share
5 answers

ParseExact reports the date format that it is expected to parse, not the format you want to receive.

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

If you want to display a date string:

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

Chris

+20

, , :

$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)

:

$InvoiceDate.ToString('yyyy-MM-dd')

'{0:yyyy-MM-dd}' -f $InvoiceDate
+4
$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

, , var, , : $newInvoice.ToString("yyyy-MM-dd") $newInvoice , , datetime - ..

+2

!

PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice

Now the type is converted. You can use the method or you can access any property.

Example :$Format_date.AddDays(5)
0
source

enter image description here

HTML color coding is required through the Power Shell script:

The attached image above is my SQL output, which should be highlighted in red, where the date is displayed older than 5 days.

0
source

Source: https://habr.com/ru/post/1649890/


All Articles