在PowerShell中将字符串转换为日期时间

74

我正在使用PowerShell尝试将字符串转换为日期时间。这应该很容易,对吧?

我从CSV文件导入字符串,其格式为Jul-16。我已经尝试了多种方法将其转换为我想要的格式yyyy-MM-dd,目前我的代码如下所示。

$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
$invoice = [datetime]::parseexact($invoice, 'yyyy-MM-dd', $null)

但是我收到了错误信息:

字符串未被识别为有效的日期时间。

我漏掉了什么吗?


1
字符串Jul-16的格式是Jul-16,那么你为什么要用yyyy-MM-dd来解析它,而不是MMM-dd?你把这个和将字符串格式化为yyyy-MM-dd混淆了。 - Jeroen Mostert
8个回答

99

ParseExact需要告知要解析的日期格式,而不是您希望得到的格式。

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

如果您希望输出日期字符串:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')

3
如果输入是已知的标准格式,您可以使用Parse而不需要提供格式,而无需使用ParseExact。 - Steve Crane

46

您可以将字符串简单地转换为DateTime:

[DateTime]"2020-7-16"
或者
[DateTime]"Jul-16"
或者
$myDate = [DateTime]"Jul-16";

你可以通过类似以下方式来格式化生成的DateTime变量:

'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
或者
$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate

1
这应该是最具声明性的解决方案,可以满足大多数用户的需求。 - ZekeC
这在某种程度上是好的。对于更复杂的字符串,例如“26/Apr/2023:16:34:14”,它将无法工作。在这些情况下需要使用ParseExact。 - jim birch

14

为了解析它,您需要指定它已经具有的格式:

$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)
现在您可以按照需要的格式输出它:
$InvoiceDate.ToString('yyyy-MM-dd')
或者
'{0:yyyy-MM-dd}' -f $InvoiceDate

5

Chris Dents的回答已经涵盖了OP的问题,但由于这是谷歌上搜索“PowerShell将格式字符串转换为日期”的最高结果,我想提供一个不同的字符串示例。


如果像我一样,您得到的时间字符串如下:20190720170000.000000+000

需要注意的重要事项是,在使用[System.Management.ManagementDateTimeConverter]时需要使用ToUniversalTime(),否则您会得到相对于输入的偏移时间。

PS代码

cls
Write-Host "This example is for the 24hr clock with HH"
Write-Host "ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
$my_date_24hr_time   = "20190720170000.000000+000"
$date_format         = "yyyy-MM-dd HH:mm"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_24hr_time,"yyyyMMddHHmmss.000000+000",$null).ToSTring($date_format)
Write-Host
Write-Host "-----------------------------"
Write-Host
Write-Host "This example is for the am pm clock with hh"
Write-Host "Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
Write-Host
$my_date_ampm_time   = "20190720110000.000000+000"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_ampm_time,"yyyyMMddhhmmss.000000+000",$null).ToSTring($date_format)

输出

This example is for the 24hr clock with HH
ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]

20 July 2019 17:00:00
2019-07-20 17:00
2019-07-20 17:00

-----------------------------

This example is for the am pm clock with hh
Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]

20 July 2019 11:00:00
2019-07-20 11:00
2019-07-20 11:00

Microsoft文档关于[Management.ManagementDateTimeConverter]:

https://learn.microsoft.com/zh-cn/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1


这个答案最终帮了我!所以我们可以检查哪一个是正确的并且可行的。我一直在寻找从 Get-WmiObject win32_process | Where-Object {$_.ProcessId -eq "2036"} 获取并格式化“CreationDate”的正确方法。 - inMILD

2
$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

在这里,使用类型加速器,但也要放到一个新变量中,如果您想在其他地方使用它,可以像这样使用:$newInvoice.ToString("yyyy-MM-dd"),因为$newInvoice始终处于日期时间格式,除非您在之后将其强制转换为字符串,但会失去执行日期时间功能(添加天数等)的能力...


1
希望下面的内容能够帮到您!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice

现在类型已转换。您可以使用方法或访问任何属性。

Example :$Format_date.AddDays(5)

0

我有一个不同但相关的需求,将一个数字(秒)转换为天/小时/秒等。

$seconds = 41414141
New-Timespan -seconds $seconds

enter image description here


0

非常容易;在我的情况下,它可以这样工作:

输入:

$Date = '29-07-2022'

日期格式转换:

[datetime]::parseexact($date, 'dd-MM-yyyy', $null).ToString('dd-MMMM-yyyy')

输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接