The Get-Date cmdlet gets the current date and time. Here is an example,
This article discusses how to format Get-Date output using two formatting options – .NET and UNIX.
In particular, we want to get the datetime output in the format yyyymmddhhmmss. In this format, “Friday, December 23, 2022 11:00:12 AM” becomes
202212110012
Get-Date Format yyyymmddhhmmss Using .NET Formatting Style
The .NET format uses the -Format parameter in Get-Date with the following formatting shorthands:
Shorthand | Meaning |
“yyyy” | The year as a four-digit number, e.g. 2009, 0100 |
“MM” | The month of the year, from 01 through 12 |
“hh” | The hour, using a 12-hour clock from 01 to 12. |
“HH” | The hour, using a 24-hour clock from 00 to 23. |
“ss” | The second, from 00 through 59. |
“mm” | The minute, from 00 through 59. |
“dd” | The day of the month, from 01 through 31. |
With those shorthands, we can now format the Get-Date command as follows
1 |
Get-Date -Format "yyyymmddhhmmss" |
You can also include separators to make the output more readable. The following example uses “/”as a date separator, whitespace between time and date, and “:” as a time separator.
1 |
Get-Date -Format "yyyy-mm-dd hh:mm:ss" |
Showing AM or PM designator (using tt format specifier)
1 |
Get-Date -Format "yyyy-mm-dd hh:mm:sstt" |
Using a 24-hour system (use HH instead of hh)
1 |
Get-Date -Format "yyyy-mm-dd HH:mm:ss" |
Using Unix Style to get yyyymmddhhmmss Datetime Format
The following formatting specifiers come in handy for our case.
Shorthand | Meaning |
%Y | The year as a four-digit format, e.g. 2009, 0198 |
%m | 2-digit month number, 01 to 12 |
%d | Day of the month – 2 digits, 01 through 31 |
%H | Hour in the 24-hour system, 00 to 23 |
%I | Hour in 12-hour format, 01 to 12 |
%M | Minutes, 00 through 59 |
%S | Seconds, from 00 to 59 |
%p | AM or PM designator |
%F | Date in yyyy-mm-dd format, equal to %Y-%m-%d, e.g. 2022-12-23. (Available in PowerShell 6.2 and later) |
%r | Time in 12-hour format, for example, 10:01:57 PM |
%T | Time in 24-hour format, e.g. 22:01:57 |
1 |
Get-Date -UFormat "%Y%m%d%H%M%S" |
Just like in the .NET format specifier, you can also use separators. For example,
1 |
Get-Date -UFormat "%Y/%m/%d %H:%M:%S" |
You can also use %F instead of %Y-%m-%d and %T in place of %H:%M:%S as follows
1 |
Get-Date -UFormat "%F %T" |
And for a 12-hour clock system with AM/PM designator, use something like this
1 |
Get-Date -UFormat "%Y-%m-%d %I:%M:%p" |
References
Get-Date cmdlet: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date
.NET format specifiers: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
UFormat specifiers: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date (at the bottom of the page)