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,
1 |
Get-Date -Format "yyyy-mm-dd HH:mm:ss.fff" |
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.
1 |
Get-Date -Format "fff" |
Here is another example with custom datetime.
1 |
Get-Date -Date "2022-12-15T12:12:50.208" -Format "yyyy-mm-dd HH:mm:ss.fff" |
Fetching Milliseconds using Get-Date cmdlet Property
The Get-Date object has the “millisecond” property you can use to get milliseconds. For example,
1 |
(Get-Date).Millisecond |
Like in the previous method, you can pass a custom datetime and fetch milliseconds in a similar way.
1 |
(Get-Date -Date "2022-12-22T12:37:52.596").Millisecond |
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.
1 |
Get-Date | Select-Object Millisecond |
1 |
Get-Date -Date "2022-12-22T12:37:52.596" | Select-Object Millisecond |
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.
1 |
(Get-Date).ToString() |
You can also pass format specifiers to (Get-Date).ToString() method as shown below
1 |
(Get-Date).ToString("yyyy/mm/dd HH:mm:ss.fff") |
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