【问题标题】:Convert string to DateTime in Powershell from CSV在 Powershell 中将字符串从 CSV 转换为 DateTime
【发布时间】:2020-09-11 23:48:01
【问题描述】:

在处理需要转换为 DateTime 的字符串时,我遇到了最奇怪和最烦人的问题。

我正在对 2 个不同的 CSV 文件执行完全相同的操作 - 它在第一个文件上完美运行,在第二个文件上不断返回错误。

$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/2021,而在第二个 CSV 中,它是 31/12/2021 0:00:00

所以在创建 $userDateOut 的 3 行之前,我会这样做

$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

我不知道为什么...有人可以帮忙吗?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    -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 将其转换回预期的输出格式:

    【讨论】:

    • 通过谷歌搜索,我找到了 DateTime ParseExact,但仅适用于 C#,无法在 Powershell 中找到。问题解决了!
    • @MichelBalencourt 在这种情况下,您可能会发现this answer 也很有用! :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2021-03-31
    • 2011-10-16
    • 2016-03-17
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多