Format a DateTime in PowerShell

  1. Use the -format Option to Format a Date and Time in PowerShell
  2. Use (Get-Date).ToString to Format a Date and Time in PowerShell
  3. Select From All Date and Time Formatting Styles Using GetDateTimeFormats() in PowerShell
  4. Format the Date and Time to Use in an HTTP header in PowerShell

This tutorial will introduce different methods to format a date and time in PowerShell. You can view the current date and time of the system using a cmdlet Get-Date.

Get-Date

Output:

Friday, December 3, 2021 5:28:16 PM

The above output is the default formatting for displaying the date and time. We will look at different examples to display the date and time in other possible formats.

Use the -format Option to Format a Date and Time in PowerShell

The following command displays the current date and time in the format of Year-Month-Day and Second:Minute:Hour, respectively.

Get-Date -format "yyyy-MM-dd ss:mm:HH"

Output:

2021-12-03 49:07:16

If you want to print the date only, you need to use the date format only. For example,

Get-Date -format "dd/MM/yyyy"

Output:

03/12/2021

Use (Get-Date).ToString to Format a Date and Time in PowerShell

Another way to change the formatting of a date and time is:

(Get-Date).ToString("dd/MM/yyyy HH:mm:ss")

Output:

03/12/2021 19:08:39

Select From All Date and Time Formatting Styles Using GetDateTimeFormats() in PowerShell

To view all the date and time formats, you can use the below command. It displays a large string array of formatting styles for date and time.

(Get-Date).GetDateTimeFormats()

Output:

12/3/2021
12/3/21
12/03/21
12/03/2021
21/12/03
2021-12-03
03-Dec-21
Friday, December 3, 2021
...
3 December, 2021 4:54:50 PM
3 December, 2021 04:54:50 PM
3 December, 2021 16:54:50
3 December, 2021 16:54:50
December 2021
December 2021

You can select one of the formatting styles from the array list with []. For example,

(Get-Date).GetDateTimeFormats()[7]

Output:

Friday, December 3, 2021

Format the Date and Time to Use in an HTTP header in PowerShell

You can use the format specifier R or r to format the date and time for use in an HTTP header. It displays the date and time in RFC1123 format.

Get-Date -format R

OR

(Get-Date).ToString("R")

Output:

Fri, 03 Dec 2021 18:11:41 GMT
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.