Converting date time format in PowerShell

谁说我不能喝 提交于 2019-12-24 10:44:11

问题


How do I convert the following date into the dd/mm/yyyy format?

Tue Aug  4 17:05:41 2015

I tried multiple things and options, but no luck.

$a = Get-Date -UFormat %c
(Get-Date $a).ToString("ddMMyyyy")

This dateformat was found in a log file and my system datetime format is dd/mm/yyyy. I am trying to do a comparison between them. So, I need to change the date time format.


回答1:


The answer from @jisaak is almost spot on, except for the fact that the extra padding space in front of the date component ("Tue Aug 4 17:05:41 2015") is going to cause an error when you try to parse a date between the 10th and 31st of the month:

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

The easiest way to go about this is to remove the padding space in both the input string and the format string:

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)
}



回答2:


Maybe primitive, but it does the job :)

$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



回答3:


You can use Datetime ParseExact method:

$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)

As Vesper mentioned, you are now able to compare datetime objects.




回答4:


Use:

Get-Date -format d

This will give you today's date, but in mm/dd/yyyy format. Be careful though; this will give you a string and not an integer.



来源:https://stackoverflow.com/questions/31808296/converting-date-time-format-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!