Mulesoft Developer
Mulesoft Developer

Reputation: 2824

Find time in milliseconds?

How can I find the time in milliseconds using PowerShell?

Upvotes: 32

Views: 97621

Answers (7)

Abel Wenning
Abel Wenning

Reputation: 650

Vignesh Narendran's answer gives the Epoch milliseconds time in UTC.

If you want it in your computer's time zone, as a string:

(Get-Date -UFormat %s).Replace('.', '').Substring(0, 13)

As a number:

[Long](Get-Date -UFormat %s).Replace('.', '').Substring(0, 13)

PowerShell 7.1 added a -AsUTC switch for Get-Date if you want UTC.

Upvotes: 0

js2010
js2010

Reputation: 27606

10,000 ticks is 1 millisecond. (1 tick is 100 nanoseconds.) Whether it has to be in UTC is another question. Microsoft ticks and filetime and unix time all count from different dates.

(get-date).ticks/10000 # local time (I'm EST -5:00)

63808255598664.8


([datetime]'1/1/2023').ticks/10000

63808128000000


([timespan]10000).TotalMilliseconds

1


([datetimeoffset]'1/1/2023').ticks/10000      # from 1/1/0001 local time

63808128000000


([datetimeoffset]'1/1/2023').ToUnixTimeMilliseconds() # from 1/1/1970 utc

1672549200000


([datetimeoffset]'1/1/2023').ToFileTime()/10000 # milliseconds from 1/1/1601 utc

13317022800000



([datetimeoffset]'1/1/0001').ticks

0


([datetimeoffset]'12/31/1969 7pm').ToUnixTimeMilliseconds()

0


([datetimeoffset]'12/31/1600 7pm').ToFileTime() # ticks

0

Upvotes: 0

Vignesh Narendran
Vignesh Narendran

Reputation: 133

This should work:

[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()

returns

1624186843769

Upvotes: 12

freakydinde
freakydinde

Reputation: 1150

You can get the full date with milliseconds with the following:

Get-Date -Format HH:mm:ss.fff

Upvotes: 61

CB.
CB.

Reputation: 60976

In PowerShell you can cast a time value to a timespan and call the TotalMilliseconds method:

([TimeSpan]"00:05:00").TotalMilliseconds # Returns 300000

([TimeSpan] (Get-Date).ToShortTimeString()).TotalMilliseconds # Returns total milliseconds from 00:00:00 till now

Upvotes: 11

Brian McMahon
Brian McMahon

Reputation: 399

The question suggests finding a given datetime in milliseconds (Microsoft epoch time). This is easily solved with:

[Math]::Round((Get-Date).ToFileTime()/10000)

or

[Math]::Round((Get-Date).ToFileTimeUTC()/10000)

To convert this to Unix epoch time in seconds:

[Math]::Round((Get-Date).ToFileTime() / 10000000 - 11644473600)

Where 11644473600 is the number of elapsed seconds between the Microsoft epoch (January 1, 1601 A.D. (C.E.)) and the Unix epoch (January 1, 1970, 12AM UTC/GMT)

https://msdn.microsoft.com/en-us/library/system.datetime.tofiletime(v=vs.110).aspx

Upvotes: 18

OldFart
OldFart

Reputation: 2479

If you need (sub-)millisecond resolution, check out System.Diagnostics.Stopwatch.

$stopwatch = New-Object System.Diagnostics.Stopwatch
$stopwatch.Start()
$stopwatch.Stop()
$stopwatch

Upvotes: 10

Related Questions