Change date format from “yyyymmdd” to “mm/dd/yyyy”

放肆的年华 提交于 2021-02-08 15:01:28

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/36562124/change-date-format-from-yyyymmdd-to-mm-dd-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!