Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ApproximateTime {
- [timespan]$Value
- [string]$Prefix
- [string]$Postfix
- [string[]]$Units
- static [string]Round([double]$Number, [string]$Unit) {
- $Number, $Half = if ((($Number % 1) -gt 0.25) -and (($Number % 1) -lt 0.75)) { ($Number - 0.5), '½' } else { $Number, '' }
- return ('{0}{1} {2}' -f [System.Math]::Round($Number, 0), $Half, $Unit)
- }
- ApproximateTime() {
- $this.Init((New-TimeSpan -Seconds 0), $null, $null, $null)
- }
- ApproximateTime([timespan]$Value) {
- $this.Init($Value, $null, $null, $null)
- }
- ApproximateTime([timespan]$Value, [string]$Prefix) {
- $this.Init($Value, $Prefix, $null, $null)
- }
- ApproximateTime([timespan]$Value, [string]$Prefix, [string]$Postfix) {
- $this.Init($Value, $Prefix, $Postfix, $null)
- }
- ApproximateTime([timespan]$Value, [string]$Prefix, [string]$Postfix, $Units) {
- $this.Init($Value, $Prefix, $Postfix, $Units)
- }
- [string]ToString() {
- [string]$result = switch ($this.Value.TotalSeconds) {
- { $_ -le 3 } { "<5 $($this.Units[0])"; break }
- { $_ -le 7.5 } { "5 $($this.Units[0])"; break }
- { $_ -le 47.5 } {
- "$([System.Math]::Round((($this.Value.TotalSeconds - 2.5) - (($this.Value.TotalSeconds - 2.5) % 5) + 5), 0)) $($this.Units[0])"
- break
- }
- { $_ -le 75 } { $this.Units[1]; break }
- { $_ -le 2700 } {
- [ApproximateTime]::Round($this.Value.TotalMinutes, $this.Units[2])
- break
- } # 45 minutes or less
- { $_ -le 4500 } { $this.Units[3]; break } # 45 minutes to 1.25 hours
- { $_ -le 173700 } {
- [ApproximateTime]::Round($this.Value.TotalHours, $this.Units[4])
- break
- } # less than 2 days 15 minutes
- default {
- [ApproximateTime]::Round($this.Value.TotalDays, $this.Units[5])
- }
- }
- return ("$($this.Prefix) $result $($this.Postfix) ".Trim())
- } # ApproximateTime
- hidden Init ([timespan]$Value, [string]$Prefix, [string]$Postfix, [string[]]$Units) {
- $this.Value = $Value
- $this.Prefix = $Prefix
- $this.Postfix = $Postfix
- $this.Units = @('seconds', 'a minute', 'minutes', 'an hour', 'hours', 'days')
- if ($Units -is [array]) {
- for ($i = 0; ($i -lt $this.Units.Count) -and ($i -lt $Units.Count); $i++) {
- $this.Units[$i] = $Units[$i]
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement