How can I parse dates and calculate the time difference in Powershell?

In Powershell, I have two variables that contain dates. How can I analyze the dates and calculate the time difference between the two dates?

$date1="6/16/2014 3:52:48 PM"
$date2="6/16/2014 4:05:53 PM"
$between=$date2-$date1
$between #Need print: 00:13:05
+4
source share
3 answers

The .NET DateTimetype has a whole set of parsing methods, including some that allow you to specify a pattern or several patterns, specifying the desired format. Having guessed a little about the format , you have:

$culture = Get-Culture
$format = "M'/'d'/'yyyy h':'mm':'ss tt"
$date1 = [DateTime]::ParseExact('6/16/2014 3:52:48 PM', $format, $culture)
$date2 = [DateTime]::ParseExact('6/16/2014 4:05:53 PM', $format, $culture)

DateTime , TimeSpan, PowerShell V3 , , .NET 4, ( "standard" "custom" , ), :

$between = $date2 - $date1
$between.ToString("hh':'mm':'ss")
$between #Need print: 00:07:05

, , 13 5 .

+4

get-date . .

$date1=get-date "6/16/2014 3:52:48 PM"
$date2=get-date "6/16/2014 4:05:53 PM"
$between=$date2-$date1
$between #Need print: 00:13:05
+2

$ date1 = [datetime] "6/16/2014 15:52:48"

$ date2 = [datetime] "6/16/2014 16:05:53"

(New-TimeSpan -Start $ date1 -End $ date2) .ToString ()

Conclusion 00:13:05

+1
source

Source: https://habr.com/ru/post/1544857/


All Articles