在 PowerShell 中通過 ParseExact 解析日期時間

Rohan Timalsina 2023年1月30日
  1. 在 PowerShell 中使用 ParseExact 方法來解析 DateTime
  2. 在 PowerShell 中使用顯式型別轉換解析 DateTime
在 PowerShell 中通過 ParseExact 解析日期時間

在 PowerShell 上處理日期時,有時你需要將日期字串轉換為 DateTime 物件。你不能使用日期字串來執行 DateTime 操作;你將需要 DateTime 物件。

本教程將教你在 PowerShell 中解析字串並將其轉換為 DateTime 格式。

在 PowerShell 中使用 ParseExact 方法來解析 DateTime

DateTime 類的 ParseExact 方法將日期和時間字串轉換為 DateTime 格式。日期和時間字串模式的格式必須與 DateTime 物件的指定格式匹配。

下面的示例使用 ParseExact 方法將日期字串轉換為 DateTime 物件。

$strDate = '2022/06/11'
[DateTime]::ParseExact($strDate, 'yyyy/MM/dd', $null)

在上述指令碼中,日期字串儲存在變數 $strDate 中。然後將其傳遞給 ParseExact 方法,後跟 DateTime 格式,該格式與日期字串的模式相匹配。

輸出:

11 June 2022 00:00:00

你可以將轉換後的 DateTime 格式儲存在變數中,並使用 GetType() 方法檢查資料型別。

$strDate = '2022/06/11'
$newDate=[Datetime]::ParseExact($strDate, 'yyyy/MM/dd', $null)
$newDate.GetType()

輸出:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DateTime                                 System.ValueType

在 PowerShell 中使用顯式型別轉換解析 DateTime

你還可以在 PowerShell 中將日期和時間字串轉換為 DateTime 格式。

使用此語法,你可以將字串強制轉換為 DateTime 物件。

[DateTime]string

以下示例使用強制轉換表示式將日期和時間的字串表示形式轉換為 DateTime 物件。

$strDate = "2022-06-11 09:22:40"
[DateTime]$strDate

輸出:

11 June 2022 09:22:40

使用 DateTime 物件,你應該能夠執行任何 DateTime 操作。我們希望本教程能幫助你瞭解如何在 PowerShell 中將字串轉換為 DateTime 格式。

作者: Rohan Timalsina
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

相關文章 - PowerShell DateTime