Roxx
Roxx

Reputation: 3986

Converting date time format in PowerShell

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.

Upvotes: 1

Views: 17417

Answers (4)

Crow
Crow

Reputation: 15

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.

Upvotes: 0

Avshalom
Avshalom

Reputation: 8889

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

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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

Upvotes: 5

Martin Brandl
Martin Brandl

Reputation: 58931

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.

Upvotes: 1

Related Questions