Fiddle Freak
Fiddle Freak

Reputation: 2041

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?

Upvotes: 6

Views: 9535

Answers (2)

Nick
Nick

Reputation: 1863

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

Upvotes: 10

mklement0
mklement0

Reputation: 437638

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.

Upvotes: 1

Related Questions