Advertisement
Old-Lost

[TimeSpan].Approximate method

May 30th, 2017
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Update-TypeData -Force -TypeName TimeSpan -MemberType ScriptMethod -MemberName Approximate -Value {
  2.     if ($args.Count -gt 1) {
  3.         throw ('Cannot find an overload for "{0}" and the argument count: "{1}".' -f 'Approximate', $Args.Count)
  4.     }
  5.     function Round([double]$Number, [string]$Unit) {
  6.         $Number, $Half = if ((($Number % 1) -gt 0.25) -and (($Number % 1) -lt 0.75)) { ($Number - 0.5), '½' } else { $Number, '' }
  7.         '{0}{1} {2}' -f [System.Math]::Round($Number, 0), $Half, $Unit
  8.     }
  9.     $Units = @('seconds', 'a minute', 'minutes', 'an hour', 'hours', 'days')
  10.     if ($args.Count -gt 0 -and $args[0] -is [array]) {
  11.         for ($i = 0; ($i -lt $Units.Count) -and ($i -lt $args[0].Count); $i++) {
  12.             $Units[$i] = $args[0][$i]
  13.         }
  14.     }
  15.     $result = switch ($this.TotalSeconds) {
  16.         { $_ -le 3 }      { "<5 $($Units[0])"; break }
  17.         { $_ -le 7.5 }      { "5 $($Units[0])"; break }
  18.         { $_ -le 47.5 }     {
  19.             "$([System.Math]::Round((($this.TotalSeconds - 2.5) - (($this.TotalSeconds - 2.5) % 5) + 5), 0)) $($Units[0])"
  20.             break
  21.         }
  22.         { $_ -le 75 }    { $Units[1]; break }
  23.         { $_ -le 2700 }   {
  24.             Round -Number $this.TotalMinutes -Unit $Units[2]
  25.             break
  26.         } # 45 minutes or less
  27.         { $_ -le 4500 }   { $Units[3]; break } # 45 minutes to 1.25 hours
  28.         { $_ -le 173700 }  {
  29.             Round -Number $this.TotalHours -Unit $Units[4]
  30.             break
  31.         } # less than 2 days 15 minutes
  32.         default {
  33.             Round -Number $this.TotalDays -Unit $Units[5]
  34.         }
  35.     }
  36.     return $result
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement