简体   繁体   中英

Converting other zone date time format to local date-time format in PowerShell

I am trying to perform date-time comparison.

Datetime in log file- Tue Aug 4 17:05:41 2015

Local system date time from get-date command -

6. elokuuta 2015 10:18:47

It's 6 Aug 2015 10:18:47 after I translated it on Google Translate.

How do I convert this date/time format, so I can perform comparison?

I tried multiple things and options, but no luck.

My script so far:

# To get today's date
$Today=[datetime]::Today
# Output is 6. elokuuta 2015 0:00:00

$log_date = "Tue Aug  4 17:05:41 2015"

I read somewhere that by using new-object system.globalization.datetimeformatinfo it can be achieved, but I don't know how to change the current date-time with this. https://technet.microsoft.com/en-us/library/ff730960.aspx

[DateTime] objects do not have a format. It just a number of ticks (0.0000001 second) passed since some point in time (01/01/0001 00:00:00.0000000). The format is only needed to save a [DateTime] object as a string or to display it to the user, since 635744160000000000 ticks is not really understandable to a user.

All you need is to parse the string to get a [DateTime] object:

$log_date = [datetime]::ParseExact('Tue Aug  4 17:05:41 2015','ddd MMM d HH:mm:ss yyyy',[cultureinfo]::InvariantCulture,'AllowInnerWhite')

Now as you have two [DateTime] objects you can compare them:

$Today -eq $log_date
$Today -lt $log_date
$Today -gt $log_date

Or find a difference between them:

$Today - $log_date

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