PowerShell 将字符串转换为日期时间
通常,在处理基于 DateTime 的操作时,我们面临的常见问题是在 PowerShell 中将字符串转换为 DateTime,以及在 PowerShell 中将 DateTime 转换为字符串。
在本文中,我将向您解释在 PowerShell 中将字符串转换为日期时间的不同方法。
您可以使用 DateTime 对象的 ParseExact 方法或将字符串转换为 DateTime 将字符串转换为 DateTime 格式。
使用 ParseExact 将字符串转换为日期时间
DateTime 类具有 ParseExact 方法,该方法使用指定的日期格式将 DateTime 的字符串表示形式转换为 DateTime。
让我们考虑一个具有 DateTime 字符串表示形式的字符串变量。使用 ParseExact() 该方法将在 PowerShell 中将字符串转换为日期时间格式。
# Using Datetime ParseExact method to convert string to datetime
$strDateTime = '06/08/2021'
[Datetime]::ParseExact($strDateTime, 'dd/MM/yyyy', $null)在上面的 PowerShell 脚本中,$strDateTime 变量包含日期时间格式。
使用 DateTime 的 ParseExact 方法,将字符串作为输入、DateTime 格式和区域性特定格式信息,并将字符串转换为 DateTime。
上述脚本在 PowerShell 中将字符串转换为日期时间格式的输出如下
PS C:\> # Using Datetime ParseExact method to convert string to datetime
$strDateTime = '06/08/2021'
[Datetime]::ParseExact($strDateTime, 'dd/MM/yyyy', $null)
06 August 2021 00:00:00
PS C:\> 如上面的输出所示,ParseExact 将字符串 DateTime 格式转换为 dd/MM/yyyy 格式 DateTime。
酷提示:如何在 PowerShell 中创建多行字符串!
使用 Cast 将字符串转换为日期时间
您可以在 PowerShell 中强制转换将字符串转换为 DateTime 格式。将字符串转换为日期时间格式。
让我们考虑下面的示例,使用强制转换将字符串转换为 DateTime
# Using cast string to datetime using DateTime
$strDateTime = "2021-07-02"
[DateTime]$strDateTime上述 PowerShell 脚本 $strDateTime 存储日期时间格式的字符串表示形式。
使用[DateTime]string,您可以将字符串转换为DateTime 格式。
酷提示:如何在 PowerShell 中使用 Get-Date 将日期转换为字符串!
上面的输出使用强制转换将字符串转换为日期时间格式,如下所示
PS C:\> # Using Datetime ParseExact method to convert string to datetime
$strDateTime = '06/08/2021'
[Datetime]::ParseExact($strDateTime, 'dd/MM/yyyy', $null)
06 August 2021 00:00:00
PS C:\> 您可以将转换后的字符串存储为 DateTime 格式的日期在变量中,并使用 DateTime 操作,如下所示
# Using cast string to datetime using DateTime
$strDateTime = "2021-07-02"
$convertDate = [DateTime]$strDateTime
# Print variable datatype
$convertDate.GetType()
# Convert datetime to dd-mm-yyyy datetime format
'{0:dd-MM-yyyy}' -f $convertDate
# Convert datetime to mm-dd-yyyy datetime format
'{0:MM-dd-yyyy}' -f $convertDate
# Convert datetime to yyyy-mmm-dd datetime format
'{0:yyyy-MMM-dd}' -f $convertDate在上面的 PowerShell 脚本中,首先,它将字符串转换为 DateTime 格式,并将 DateTime 值存储在 $convertDate 变量中。
$convertDate 变量具有 DateTime 数据类型,使用 GetType() 方法获取变量的数据类型。
酷提示:如何在 PowerShell 中使用 noprofile 参数执行脚本!
一旦有了 DateTime 变量,您就可以执行任何类型的 DateTime 操作,例如以不同的 DateTime 格式(如 dd-mm-yyyy 或 mm-dd-yyyy 或任何其他有效的日期时间格式)打印 DateTime。
上述PowerShell脚本的输出如下
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
02-07-2021
07-02-2021
2021-Jul-02酷提示:如何在 PowerShell 中创建多行注释!
结论
我希望上面关于使用 PowerShell 将字符串转换为 DateTime 格式的文章对您在执行 DateTime 操作时有所帮助。
使用 DateTime ParseExact() 方法或转换为日期时间格式将字符串转换为日期时间。
您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。
推荐内容
PowerShell 新纪元时间和日期时间转换
PowerShell 获取日期减去 1 天
PowerShell 比较日期
PowerShell 将日期时间转换为字符串
