4

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Sure 13 minutes. It's my mistake. Thanks a lot!
2

I would just use get-date with the provided strings. That will use the current culture and is much simpler.

$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

Comments

1

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

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

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

The output is 00:13:05

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.