在PowerShell中转换日期时间格式 [英] Converting date time format in PowerShell

查看:16
本文介绍了在PowerShell中转换日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下日期转换为dd/mm/yyyy格式?

Tue Aug  4 17:05:41 2015

我尝试了多种方法和选项,但没有成功。

$a = Get-Date -UFormat %c
(Get-Date $a).ToString("ddMMyyyy")
此日期格式是在日志文件中找到的,而我的系统日期时间格式为dd/mm/yyyy。 我正在试着对它们进行比较。于是,我需要更改日期时间格式。

推荐答案

@jisaak的答案几乎是Spot On,只是Date组件前面的额外填充空格("Tue Aug42015")会在您尝试解析介于月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)
}

这篇关于在PowerShell中转换日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆