In Powershell I have got two variables which contain dates. How can I parse the dates and calculate the time differences between 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
.NET's DateTime
type has a whole set of parsing methods, including some that allow you to specify a pattern, or multiple patterns, specifying the format you want. With a slight guess at 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)
If you subtract one DateTime
from another you'll get a TimeSpan
instance, if you are using PowerShell V3 or latter, thus using .NET 4 this has considerably more formatting options ("standard" and "custom" are both available, I use custom below) than earlier versions:
$between = $date2 - $date1
$between.ToString("hh':'mm':'ss")
$between #Need print: 00:07:05
I think you'll find the difference is 13 minutes 5 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With