Iro*_*nic 1 powershell powershell-2.0 powershell-3.0
如何将以下日期转换为dd/mm/yyyy格式?
Tue Aug 4 17:05:41 2015
Run Code Online (Sandbox Code Playgroud)
我尝试了多种方法和选择,但没有运气.
$a = Get-Date -UFormat %c
(Get-Date $a).ToString("ddMMyyyy")
Run Code Online (Sandbox Code Playgroud)
此日期格式在日志文件中找到,我的系统日期时间格式为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
Run Code Online (Sandbox Code Playgroud)
最简单的方法是删除输入字符串和格式字符串中的填充空间:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8981 次 |
| 最近记录: |