Forum Discussion

gugugu's avatar
gugugu
Copper Contributor
May 10, 2022

Powershell days different output result is not a day number

When I use

$Date1 - $Date2

output result is not a time number

 

$Date1
$Date2
$Date1 - $Date2

 

the result is shown as below

how can i get days in a number?

 

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    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

    • gugugu's avatar
      gugugu
      Copper Contributor

      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?

       

       

       

      • LainRobertson's avatar
        LainRobertson
        Silver Contributor

        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.

         

         

        Similarly, New-TimeSpan returns the same result.

         

         

        Cheers,

        Lain

Resources