简体   繁体   English

在Powershell中将字符串转换为日期时间

[英]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: 我正在尝试解析文件名(字符串),并使用以下行将它们转换为PowerShell中的日期:

([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. 只需将呼叫放在try..catch块中。 I would recommend using InvariantCulture rather than $null , though. 我建议使用InvariantCulture而不是$null

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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