我的日期为字符串,格式如下:
July 27th, 2016
December 3rd, 2014
August 1st, 1998
March 2nd, 1979
如何使用PowerShell将日期转换为以下内容
2016-07-27
2014-12-03
1998-08-01
1979-03-02
答案 0 :(得分:2)
我会选择使用某些正则表达式ParseExact()
来删除所有的,rd' s。
您只需在ToString()
编辑根据@JosefZ建议更新代码。
foreach ($date in @(
'July 27th, 2016'
'December 3rd, 2014'
'August 1st, 1998'
'March 2nd, 1979'
)) {
$clean = $date -replace '(st|nd|rd|th),'
$dateObject = [datetime]::ParseExact($clean, 'MMMM d yyyy', [System.Globalization.CultureInfo]::InvariantCulture)
# Apparently, this works too ...
$dateObject = [datetime]$clean
$dateObject.ToString('yyyy-MM-dd')
}
答案 1 :(得分:1)
我没有足够的代表来评论BartekB的解决方案,所以这里只是他的答案的一个小正则表达式替代。
foreach ($oldformat in @(
'July 27th, 2016'
'December 3rd, 2014'
'August 1st, 1998'
'March 2nd, 1979')
)
{
$newformat = [datetime][regex]::replace($oldformat,' *..,',"") | Get-Date -Format "yyyy-MM-dd"
Write-Host $newformat
}
答案 2 :(得分:0)
除了@ Andrii-Matus,@ BagekB所示的方法之外,以下是另一种实现同样目的的方法。
$date_str = @(
'July 27th, 2016'
'December 3rd, 2014'
'August 1st, 1998'
'March 2nd, 1979'
)
foreach ($date in $date_str){
$newformat = $date -replace '(st|nd|rd|th),'
get-date $newformat -UFormat "%Y-%m-%d"
}