Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date format from "yyyymmdd" to "mm/dd/yyyy"

I've tried a lot of different ways and I can't seem to get it right.

Here is the code of what I have tried so far...

[String]$dateValue = '20161212'
[String]$dateStamp = $dateValue -f (Get-Date)
[String]$dateStamp2 = ([datetime]::parseexact($dateValue, "yyyyMMdd", [System.Globalization.CultureInfo]::InvariantCulture)).Date
[String]$dateStamp3 = ([datetime]::FromFileTime($dateValue)).ToString('g')

Write-Host '$dateStamp  = ' $dateStamp
Write-Host '$dateStamp2 = ' $dateStamp2
Write-Host '$dateStamp3 = ' $dateStamp3

Current Code Output

$dateStamp = 20161212
$dateStamp2 = 12/12/2016 00:00:00
$dateStamp3 = 12/31/1600 5:00 PM

Desired Code Output

$dateStamp = 12/12/2016

Any Ideas?

like image 933
Fiddle Freak Avatar asked Apr 12 '16 01:04

Fiddle Freak


2 Answers

Once you have a datetime object it's easy to convert it to whatever string format you need. You are so close with your second attempt. Adding ToString allows you to specify a string format.

([datetime]::parseexact($dateValue, "yyyyMMdd", [System.Globalization.CultureInfo]::InvariantCulture)).ToString("dd/MM/yyyy")
like image 124
Nick Avatar answered Oct 20 '22 13:10

Nick


Given that you have a culture-invariant string as your input and that you want a fixed output format, you may as well perform string parsing, without the need to convert to an intermediate [datetime] instance:

> '20161213' -replace '\d{2}(\d{2})(\d{2})(\d{2})', '$2/$3/$1'
12/13/16

Note that I've changed the day to be different from the month to better highlight the reformatting that takes place.

Generally, though, the [datetime]-based method demonstrated in Nick's helpful answer gives you the most flexibility.

like image 39
mklement0 Avatar answered Oct 20 '22 12:10

mklement0