在Powershell中将字符串转换为日期时间 [英] Converting string to date time in powershell

查看:1311
本文介绍了在Powershell中将字符串转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析文件名(字符串),并使用以下行将其转换为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.

推荐答案

我不会费心检查,只需将呼叫放入 try..catch 块。我建议使用 InvariantCulture 而不是 $ null

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
}

这篇关于在Powershell中将字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆