Home > Software engineering >  Calculate Time difference using powershell
Calculate Time difference using powershell

Time:02-10

I would like to calculate Time difference between two time stamps in seconds

$starttime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")
$endtime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")

$tdiff = $starttime-$endtime

Write-Output $tdiff.seconds

The above code throws the below error:

Cannot convert value "2022-02-10T11:40:07" to type "System.Int32". Error: "Input string was not in a correct format."

Appreciate, if any one can help

CodePudding user response:

It is actually much simpler than that.

$StartDate=(GET-DATE)

$EndDate=[datetime]”01/01/2014 00:00”

NEW-TIMESPAN –Start $StartDate –End $EndDate

This is an example from Microsoft Devblogs https://devblogs.microsoft.com/scripting/powertip-get-time-difference-between-dates-with-powershell/

CodePudding user response:

You are converting the date to String in the code. You can't perform the substract operation on string values.

Try below:

$startdate = (Get-Date)
$Enddate = (Get-Date).AddDays(1)
$diff = New-TimeSpan -Start $startdate -End $Enddate 
$diff.Days
  • Related