![](/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.