如何在 powershell 中将日期为 20.02.2017 的字符串数组转换为 yyyyMMdd 格式

How to convert a string array with dates like 20.02.2017 to yyyyMMdd format in powershell

我有一个数组列表,其中包含如下所示的字符串

17.2.2017 28.2.2017 1.3.2017

我想将其转换为 yyyyMMdd 格式,以便我可以将这些日期与当前日期进行比较。我试过使用 ParseExact 但它没有用。

`

可能取决于您的语言环境,但可以从以下内容开始:

$d,$m,$y = "28.2.2017" -split "\."
$date = [DateTime]::Parse($("{0}/{1}/{2}" -f $m, $d, $y))
$date.ToString("yyyyMMdd")

根据需要进行调整以消耗您的阵列。

你可以试试:

$a ="17.2.2017 28.2.2017 1.3.2017"
$a -split ' ' | % {$b = $_ -split '\.'; Get-Date -Day $b[0] -Month $b[1] -Year $b[2]}

如果你有一个日期数组,你只需删除第一个拆分:

$a ="17.2.2017","28.2.2017","1.3.2017"
$a | % {$b = $_ -split '\.'; Get-Date -Day $b[0] -Month $b[1] -Year $b[2]}

只为一次约会:

$a ="17.2.2017"
$b = $a -split '\.'
$date = Get-Date -Day $b[0] -Month $b[1] -Year $b[2]}
$sate.ToString("yyyyMMdd")
$d,$m,$y='28.2.2017'.split('.')
'0'*(4-$y.length)+$y+'0'*(2-$m.length)+$m+'0'*(2-$d.length)+$d
#you can format string to date like this
[DateTime]::ParseExact("17.2.2017", 'd.M.yyyy', $null)

#for your string with all dates
$dates="17.2.2017 28.2.2017 11.03.2017"
-split $dates | %{[System.DateTime]::ParseExact($_, 'd.M.yyyy', $null)}

这就是我所做的并且有效。

$Date1 = -split $Date | %{[System.DateTime]::ParseExact($_, 'd.M.yyyy', $null)} $Date2 = $Date1.ToString("yyyyMMdd")