แปลงสตริงเป็น DateTime ใน Powershell จาก CSV

Sep 12 2020

ฉันมีปัญหาที่แปลกและน่ารำคาญที่สุดในการจัดการกับสตริงที่นี่ซึ่งฉันต้องแปลงเป็น DateTime

ฉันกำลังทำสิ่งเดียวกันจากไฟล์ CSV 2 ไฟล์ที่แตกต่างกัน - มันทำงานได้อย่างสมบูรณ์แบบในไฟล์แรกและส่งคืนข้อผิดพลาดในไฟล์ที่สอง

$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"

ใน CSV แรก Date_OUT เป็นเพียงตัวอย่างและในหนึ่งวินาทีมัน31/12/202131/12/2021 0:00:00

ดังนั้นก่อนสร้าง 3 บรรทัด$userDateOutฉันจะทำ

$userDateOut = $sourceLine.Date_OUT.SubString(0,10)

ซึ่งทำให้ฉันลงเอยด้วยตัวแปรประเภทเดียวกันกับ CSV ตัวแรก

PS C:\Windows\system32> $userDateOut = $sourceLine.Date_Out.Substring(0,10) PS C:\Windows\system32> $userDateOut
31/12/2021
PS C:\Windows\system32> $userDateOut.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

อย่างไรก็ตามด้วยตัวแปรนี้ฉันได้รับ

PS C:\Windows\system32> $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy" Get-Date : Cannot bind parameter 'Date'. Cannot convert value "31/12/2021" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At line:1 char:25 + $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
+                         ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

และฉันไม่รู้ว่าทำไม ... มีใครช่วยได้บ้าง?

คำตอบ

3 MathiasR.Jessen Sep 11 2020 at 22:45

-Formatเพียงแค่แปลง[datetime]ไป[string]- มันไม่ได้มีผลต่อการแยกของสายการป้อนข้อมูลในการใด ๆทาง

สำหรับสิ่งนั้นคุณต้อง[datetime]::ParseExact():

$dateString = '31/12/2021' # You can pass multiple accepted formats to ParseExact, this should cover both CSV files $inputFormats = @(
  'dd/MM/yyyy H:mm:ss'
  'dd/MM/yyyy'
)

$parsedDatetime = [datetime]::ParseExact($dateString, $inputFormat, $null)

จากนั้นคุณสามารถใช้Get-Date -Formatเพื่อแปลงกลับเป็นรูปแบบผลลัพธ์ที่ต้องการได้หากจำเป็น: