get-date Format Milliseconds in Powershell

A millisecond is a thousandth of a second. Get-Date, by default, gets the current datetime without milliseconds. For example,

There are a few ways to get the milliseconds in the Get-Date Object. We will discuss three of them in this article.

Get Millisecond using a .NET Format Specifier

The “fff” specifier can be supplied to the -Format parameter of the Get-Date cmdlet to get milliseconds in DateTime, for example,

In the example above, 435 is the milliseconds we are interested in.

You can also get the milliseconds only in the Get-Date object as follows.

Here is another example with custom datetime.

Fetching Milliseconds using Get-Date cmdlet Property

The Get-Date object has the “millisecond” property you can use to get milliseconds. For example,

Like in the previous method, you can pass a custom datetime and fetch milliseconds in a similar way.

Using the Select-Object cmdlet to get Millisecond

In this method, you pipe the output of the Get-Date cmdlet to Select-Object to fetch Milliseconds.

Bonus: Convert Get-Date Object Type into String

In some environments, for example, when writing SQL queries on PowerShell, it is necessary to convert the Get-Date output to string if you want to parse Milliseconds accurately.

The Get-Date object is converted to string by default when you use the -Format parameter, as we did in the first section.

However, the Get-Date object type is returned when working with the “millisecond” property, as discussed in the second section. In this case, we need to use the method (Get-Date).ToString() explicitly converts the DateTime object to a String.

You can also pass format specifiers to (Get-Date).ToString() method as shown below

Conclusion

This article 3 ways of getting milliseconds from the Get-Date cmdlet – using format specifiers, selecting the “millisecond” property on the Get-Date object, and using the Select-Object command. You can see more format specifiers in the documentation linked below

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings