Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a timespan from milliseconds in powershell?

Tags:

powershell

New-Timespan takes no "MilliSeconds" parameter, how do you create a TimeSpan from milliseconds?

like image 419
Marius Avatar asked Jun 02 '16 04:06

Marius


2 Answers

Use the FromMilliseconds static method of the TimeSpan structure...

PS> [TimeSpan]::FromMilliseconds(10)


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 10
Ticks             : 100000
TotalDays         : 1.15740740740741E-07
TotalHours        : 2.77777777777778E-06
TotalMinutes      : 0.000166666666666667
TotalSeconds      : 0.01
TotalMilliseconds : 10

A TimeSpan ultimately represents its duration as a number of Ticks, so if you prefer to think of it that way you can multiple the number of milliseconds by the TicksPerMillisecond constant and pass that to the constructor that accepts the number of ticks (there is no FromTicks() method)...

PS> New-Object -TypeName 'TimeSpan' -ArgumentList (10 * [TimeSpan]::TicksPerMillisecond)

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 10
Ticks             : 100000
TotalDays         : 1.15740740740741E-07
TotalHours        : 2.77777777777778E-06
TotalMinutes      : 0.000166666666666667
TotalSeconds      : 0.01
TotalMilliseconds : 10


PS> [TimeSpan]::new(10 * [TimeSpan]::TicksPerMillisecond)

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 10
Ticks             : 100000
TotalDays         : 1.15740740740741E-07
TotalHours        : 2.77777777777778E-06
TotalMinutes      : 0.000166666666666667
TotalSeconds      : 0.01
TotalMilliseconds : 10
like image 157
Lance U. Matthews Avatar answered Nov 08 '22 11:11

Lance U. Matthews


Positive: [timespan]'0:0:0.001' or [timespan]'00:00:00:00.001'

Negative: [timespan]'-0:0:0.001' or [timespan]'-00:00:00:00.001'

Specifying 4 or 5 [int32] numbers get interpreted as (optionally days,) hours, minutes, seconds and milliseconds.

For a more complete answer see https://devblogs.microsoft.com/scripting/weekend-scripter-understanding-timespan-objects/ and scroll down to TimeSpan constructors.

Each time unit specified must stay within its usual limits (0-23 for hours, 0-59 for minutes and seconds, 0-999 for milliseconds). The days range (if specified) is 0-10675199.

The highest possible [timespan] value appears to be [timespan]'10675199:2:48:5.477' (verified on PowerShell 5.1 and pwsh 7.1.1).

like image 1
G-e-V-e Avatar answered Nov 08 '22 11:11

G-e-V-e