问题
When tried converting I received the following error message apparently because of the th
symbols.
Cannot convert value "June 6th 2017, 08:09:05.000" to type "System.DateTime". Error: "The string was not recognized as a valid DateTime. There is an unknown word starting at index 6.
回答1:
The simplest method is probably to remove those characters. I'm pretty sure you could do this with Parse or ParseExact but I would just op for remove the "th" instead for the ease.
$date = "June 6th 2017, 08:09:05.000"
$date = $date -replace "(\d)(th|nd|st|rd)",'$1'
[datetime]$date
Replace "th" etc. if preceded by a number. If you happen to have dates that do not have those characters nothing would happen so there is no risk there. It would not be safe just to remove the letters outright with $date = $date -replace "th|nd|st|rd"
because of months like August.
For completeness sake there is a way that you can use parseexact()
to get this.
[DateTime]::ParseExact($date, "MMMM d\t\h yyyy, HH:mm:ss.FFF", [System.Globalization.CultureInfo]::InvariantCulture)
So that works and covers the one base. If would be harder with the other number suffixes so the first suggestion is better.
回答2:
remove the 'th' part. You can replace that with nothing and finally after removing the comma will solve your purpose to parse it.
$a="June 6th 2017, 08:09:05.000"
[System.DateTime]"$($a.Replace("th",'').Replace(',',''))"
Output:
06 June 2017 08:09:05
Hope it helps
回答3:
As everyone else suggested, you need to get rid of 'nd', 'th' etc., if they exist. I would use replace like this:
[datetime]("June 6th 2017, 08:09:05.000" -replace '(\d+)\w{2}\s','$1 ')
[datetime]("June 6 2017, 08:09:05.000" -replace '(\d+)\w{2}\s','$1 ')
[datetime]("6 June 2017, 08:09:05.000" -replace '(\d+)\w{2}\s','$1 ')
They all return:
Tuesday, June 06, 2017 8:09:05 AM
回答4:
That works:
$DateFull -replace "nd",'' -replace "st",'' -replace "rd",'' -replace "th",''
来源:https://stackoverflow.com/questions/45864607/in-powershell-how-can-i-convert-the-date-june-6th-2017-080905-000-to-datet