PowerShell, why does CreationTime expect US date format while system has European date format?
I've digitised my old VHS tapes and it's now quite a lot of separate files. I want to set the filedates to the 'original' dates of the events, so that I can sort them chronologically.
This can be done with PowerShell using CreationTime and LastWriteTime, but there is something I do not understand. My system date format is European, so DD-MM-YYYY but CreationTime only accepts US date format so MM/DD/YYYY (same goes for LastWriteTime). See code below, it's PS v4.0 btw.
# This gives error message: Cannot convert value "31-12-1998" to type "System.DateTime"
(Get-ChildItem oud_en_nieuw_beijum.mpg).CreationTime = '31-12-1998'
# This works correctly
(Get-ChildItem oud_en_nieuw_beijum.mpg).CreationTime = '12/31/1998'
# This gives error message: Cannot convert value "12/31/1998" to type "System.DateTime"
Get-Date -Date '12/31/1998'
# This works correctly
Get-Date -Date '31-12-1998'It seems that CreationTime and Get-Date use the opposite date formats? Is there some logic behind this, or am I missing something?
2 Answers
What you're trying to do now, is cast a string (the date) directly to a datetime object (The CreationTime Property)
If you cast a string to datetime, you can only use two formats, en-US Culture or ISO 8601 format (also known as japanese datetime format). Read more about that here:
So you have three options now:
- Use ISO Format:
(Get-ChildItem oud_en_nieuw_beijum.mpg).CreationTime = "1998-12-31" - Use en-US:
(Get-ChildItem oud_en_nieuw_beijum.mpg).CreationTime = "12/31/1998" - Parse:
(gci oud_en_nieuw_beijum.mpg).CreationTime = ([datetime]::Parse("31.12.1998"))
if you parse() it, PowerShell will parse the string, with your local culture info, so that way it can handle "european format"
if you want to parse a culture info that's different from your local culture, you can just create a [cultureinfo] object and parse the date. e.g:
$dateString = '10.12.2018'
$frenchCulture = [cultureinfo]::GetCultureInfo('fr-FR')
# Parsing with French Culture
[datetime]::Parse($dateString, $frenchCulture) 3 I used (Get-Item Filename.extension).CreationTime=("6 October 2020 17:47:22") and it totally works.
Same thing if you use it for LastWriteTime and LastAccessTime.