#PSTip Handling negative TimeSpan objects

Let’s say you created a new TimeSpan object by using the Start parameter.

PS> $ts = New-TimeSpan -Start 1/1/2014
PS> $ts

Days              : -324
Hours             : -9
Minutes           : -44
Seconds           : -12
Milliseconds      : -596
Ticks             : -280286525960331
TotalDays         : -324.405701342976
TotalHours        : -7785.73683223142
TotalMinutes      : -467144.209933885
TotalSeconds      : -28028652.5960331
TotalMilliseconds : -28028652596.0331

You ended up with an object whose value is negative because the start date is greater than the end date. PowerShell assigns the current date to the End parameter if no value has been specified. So, what do you do if you need a positive value? If you send the object to the Get-Member cmdlet you’ll notice a method called Negate.

PS> $ts | Get-Member -MemberType Method

   TypeName: System.TimeSpan

Name        MemberType Definition
----        ---------- ----------
Add         Method     timespan Add(timespan ts)
CompareTo   Method     int CompareTo(System.Object value), int CompareTo(timespan value), int IComparable.CompareTo(...
Duration    Method     timespan Duration()
Equals      Method     bool Equals(System.Object value), bool Equals(timespan obj), bool IEquatable[timespan].Equals...
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
Negate      Method     timespan Negate()
Subtract    Method     timespan Subtract(timespan ts)
ToString    Method     string ToString(), string ToString(string format), string ToString(string format, System.IFor...

All you need to do is invoke it.

PS> $ts.Negate()

Days              : 324
Hours             : 9
Minutes           : 44
Seconds           : 12
Milliseconds      : 596
Ticks             : 280286525960331
TotalDays         : 324.405701342976
TotalHours        : 7785.73683223142
TotalMinutes      : 467144.209933885
TotalSeconds      : 28028652.5960331
TotalMilliseconds : 28028652596.0331

Likewise, invoking the method on a positive object gives you back a negative instance.

Filed in: Columns, Tips and Tricks Tags: , ,

2 Responses to "#PSTip Handling negative TimeSpan objects"

  1. PetSerAl says:

    Unary minus do the same thing: -$ts
    And if you need positive value, you can use Duration method, which work as [Math]::Abs for TimeSpan.

  2. Very helpful Shay. Thank you for posting.

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: