简体   繁体   中英

Converting string to date time in powershell

I am trying to parse filenames (strings) and convert them to dates in powershell using the following line:

([datetime]::ParseExact($DirName.BaseName,'yyyyMMdd',$null)

The problem is, not all of the folders in that directory following that naming convention. How would I first test to see if the folder fits the naming convention and if it does, convert it to a date time object? Any help would be greatly appreciated.

I wouldn't bother checking first. Just put the call in a try..catch block. I would recommend using InvariantCulture rather than $null , though.

$culture = [Globalization.CultureInfo]::InvariantCulture
try {
  [datetime]::ParseExact($DirName.BaseName, 'yyyyMMdd', $culture)
} catch {
  # not a valid date
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM