Search code examples
powershelldatetime-formatdata-conversionstring-to-datetime

PowerShell: Weird date format string to date time


I am having trouble handling a weird date format exported from an event log.

It looks like the following: Mon May 14 09:32:59 UTC 2018

And I attempted generic Get-date, all the way to:

$stringToDatetime2 = [Datetime]::ParseExact("$($TaskFailures[0].time)", "ddd MMM dd HH:mm:ss ZZZ yyyy", $null)

I have a feeling I am probably doing something wrong that is obvious. That is the type of feeling I am getting.


Solution

  • The question you're asking is "how do I get [DateTime]::ParseExact to treat 'UTC' as '+0000'?".

    I couldn't get that to work, but I did get the following to work:

    [DateTimeOffset]::ParseExact(
        "Mon May 14 09:32:59 UTC 2018".Replace("UTC", "+0000"),
        "ddd MMM dd HH:mm:ss zzz yyyy",
        [CultureInfo]::InvariantCulture)
    

    Note the (cheating) .Replace.

    Unfortunately, I can't find a reliable way to recognise all of the timezone abbreviations. If your log file is only ever in UTC (most are, because servers are usually timezone-agnostic, and configured in UTC), you'll be fine.