Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse dates and calculate time differences in Powershell?

Tags:

powershell

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
like image 388
user3231442 Avatar asked Mar 20 '23 07:03

user3231442


1 Answers

.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.

like image 114
Richard Avatar answered Apr 26 '23 14:04

Richard