简体   繁体   English

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

[英]Convert a string to datetime in PowerShell

I am using PowerShell to try and convert a string to a datetime.我正在使用 PowerShell 尝试将字符串转换为日期时间。 It should be easy, right?应该很容易吧?

I am getting the string from a CSV import, and it comes in the format of Jul-16 .我从 CSV 导入中获取字符串,它的格式为Jul-16 I have tried multiple ways of getting it into the format I want which is yyyy-MM-dd and I am currently at the following.我已经尝试了多种方法将其转换为我想要的格式,即yyyy-MM-dd ,我目前处于以下状态。

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

But I get the error:但我得到错误:

String was not recognized as a valid DateTime.字符串未被识别为有效的日期时间。

Am I missing something?我错过了什么吗?

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out. ParseExact 被告知它预期解析的日期格式,而不是您希望得到的格式。

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

If you then wish to output a date string:如果您希望输出日期字符串:

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

Chris克里斯

You need to specify the format it already has , in order to parse it:您需要指定它已经具有的格式,以便解析它:

$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)

Now you can output it in the format you need:现在您可以以您需要的格式输出它:

$InvoiceDate.ToString('yyyy-MM-dd')

or

'{0:yyyy-MM-dd}' -f $InvoiceDate

You can simply cast strings to DateTime:您可以简单地将字符串转换为 DateTime:

[DateTime]"2020-7-16"

or

[DateTime]"Jul-16"

or

$myDate = [DateTime]"Jul-16";

And you can format the resulting DateTime variable by doing something like this:您可以通过执行以下操作来格式化生成的 DateTime 变量:

'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'

or

([DateTime]"Jul-16").ToString('yyyy-MM-dd')

or

$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate
$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

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

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd") as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...你去吧,使用类型加速器,但也进入一个新的 var,如果你想在其他地方使用它,像这样使用它: $newInvoice.ToString("yyyy-MM-dd")因为$newInvoice将始终在日期时间格式,除非您之后将其转换为字符串,但将失去执行日期时间功能的能力 - 添加天数等...

Chris Dents' answer has already covered the OPs' question but seeing as this was the top search on google for PowerShell format string as date I thought I'd give a different string example. Chris Dents 的回答已经涵盖了 OP 的问题,但看到这是 google 上PowerShell format string as date的顶级搜索,我想我会给出一个不同的字符串示例。


If like me, you get the time string like this 20190720170000.000000+000如果像我一样,你会得到这样的时间字符串20190720170000.000000+000

An important thing to note is you need to use ToUniversalTime() when using [System.Management.ManagementDateTimeConverter] otherwise you get offset times against your input.需要注意的重要一点是,在使用[System.Management.ManagementDateTimeConverter]时,您需要使用ToUniversalTime() ,否则您会根据输入获得偏移时间。

PS Code 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)

Output输出

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

MS doc on [Management.ManagementDateTimeConverter] : [Management.ManagementDateTimeConverter]上的 MS 文档:

https://docs.microsoft.com/en-us/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1 https://docs.microsoft.com/en-us/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1

Hope below helps!希望以下有帮助!

PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice

Now type is converted.现在类型已转换。 You can use method or can access any property.您可以使用方法或可以访问任何属性。

Example :$Format_date.AddDays(5)

It's very easy;这很容易; in my case it works with;就我而言,它适用于;

Input:输入:

$Date = '29-07-2022'

DateFormat Convertion:日期格式转换:

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

Output: Output:

在此处输入图像描述

I had a different but related need to convert a number (seconds) into days/hours/seconds etc.我有一个不同但相关的需要将数字(秒)转换为天/小时/秒等。

$seconds = 41414141
New-Timespan -seconds $seconds

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM