Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Comparing dates

Tags:

powershell

I am querying a data source for dates. Depending on the item I am searching for, it may have more than date associated with it.

get-date ($Output | Select-Object -ExpandProperty "Date") 

An example of the output looks like:

Monday, April 08, 2013 12:00:00 AM Friday, April 08, 2011 12:00:00 AM 

I would like to compare these dates and return which one is set further out into the future.

like image 819
pizzim13 Avatar asked Feb 23 '11 21:02

pizzim13


People also ask

How do I compare two date dates?

Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates.


2 Answers

As Get-Date returns a DateTime object you are able to compare them directly. An example:

(get-date 2010-01-02) -lt (get-date 2010-01-01) 

will return false.

like image 86
Anders Zommarin Avatar answered Sep 25 '22 06:09

Anders Zommarin


I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 ")) 

Object created:

PS> $Obj   Days              : 0 Hours             : 0 Minutes           : 31 Seconds           : 0 Milliseconds      : 0 Ticks             : 18600000000 TotalDays         : 0.0215277777777778 TotalHours        : 0.516666666666667 TotalMinutes      : 31 TotalSeconds      : 1860 TotalMilliseconds : 1860000 

Access an item directly:

PS> $Obj.Minutes 31 
like image 45
Mike Q Avatar answered Sep 24 '22 06:09

Mike Q