![](/img/trans.png)
[英]Converting other zone date time format to local date-time format in PowerShell
[英]Converting date time format in PowerShell
如何將以下日期轉換為dd / mm / yyyy格式?
Tue Aug 4 17:05:41 2015
我嘗試了多種方法和選項,但是沒有運氣。
$a = Get-Date -UFormat %c
(Get-Date $a).ToString("ddMMyyyy")
在日志文件中找到此dateformat,我的系統日期時間格式為dd / mm / yyyy。 我正在嘗試對它們進行比較。 因此,我需要更改日期時間格式。
@jisaak的答案幾乎是正確的,除了日期分量前面的多余填充空間(“ Tue Aug 4 17:05:41 2015”)會在您嘗試解析日期:每月的10號到31號:
PS C:\> [Datetime]::ParseExact('Tue Aug 4 17:05:41 2015', 'ddd MMM d HH:mm:ss yyyy', $us)
Tuesday, August 04, 2015 5:05:41 PM
PS C:\> [Datetime]::ParseExact('Tue Aug 11 17:05:41 2015', 'ddd MMM d HH:mm:ss yyyy', $us)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:1
+ [Datetime]::ParseExact('Tue Aug 11 17:05:41 2015', 'ddd MMM d HH:mm:ss yyyy', $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
最簡單的方法是刪除輸入字符串和格式字符串中的填充空間:
function Parse-CustomDate {
param(
[Parameter(Mandatory=$true)]
[string]$DateString,
[string]$DateFormat = 'ddd MMM d HH:mm:ss yyyy',
[cultureinfo]$Culture = $(New-Object System.Globalization.CultureInfo -ArgumentList "en-US")
)
# replace double space by a single one
$DateString = $DateString -replace '\s+',' '
[Datetime]::ParseExact($DateString, $DateFormat, $Culture)
}
也許是原始的,但它能完成工作:)
$Date = 'Tue Aug 4 17:05:41 2015' -split "\s"
$Year = $Date[-1]
$Time = $Date | ? {$_ -match "..:..:.."}
$DayName = $Date[0]
$Day = $Date[3]
$Month = $Date[1]
Get-Date "$Month $Day $Year $Time" -Format "ddMMyyy"
04082015
您可以使用Datetime ParseExact方法:
$us = New-Object system.globalization.cultureinfo("en-US")
[Datetime]::ParseExact('Tue Aug 4 17:05:41 2015', 'ddd MMM d HH:mm:ss yyyy', $us)
如Vesper所述,您現在可以比較日期時間對象。
采用:
Get-Date -format d
這將為您提供今天的日期,但格式為mm/dd/yyyy
。 但是要小心; 這會給你一個string
而不是integer
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.