Powershell days different output result is not a day number

Copper Contributor

When I use

$Date1 - $Date2

output result is not a time number

 

$Date1
$Date2
$Date1 - $Date2

 

the result is shown as below

xuedong2180_0-1652152396095.png

how can i get days in a number?

 

3 Replies

@gugugu 

 

Yes, that's correct. Any [datetime] arithmetic results in what you're seeing, which is a [timespan] object (TimeSpan Struct (System) | Microsoft Docs).

 

The simplest way to get the difference in days is:

 

($Date1 - $Date2).Days

 

If the value of Days is negative, that just means that $Date2 is greater than $Date1.

 

Cheers,

Lain

@LainRobertson 

 

Thank for you reply

 

You can see the image i used $date1 is 2022/08/05 $date2 is 2022/05/10.

So result shoud not a negative number.

 

And I think result is not a timestamp.because I use this

[DateTime]::FromFileTimeUTC($Date1 - $Date2).days

cant't be result to a date.

 

I got the same result using New-TimeSpan,

(New-TimeSpan -Start $Date2 -End $Date1).Days

but what MS says about New-TimeSpan  -days shoud be a number (Int32).

 

I want get the result be a "days"(number) not a timestamp .

 

have you get a good idea?

 

 

 

@gugugu 

 

So, your first command is not going to work as it's mixing data types.

 

The call to FromFileTimeUTC is expecting an Int64, not a Timespan - which is what you get from "$Date1 - $Date2".

 

The simplest way to get the days is as shown below.

 

LainRobertson_0-1652158601870.png

 

Similarly, New-TimeSpan returns the same result.

 

LainRobertson_1-1652158721258.png

 

Cheers,

Lain