简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM