PowerShell: How to Use Get-Date with 24-Hour Format


You can use the Get-Date cmdlet in PowerShell to get the current date and time.

By default, the time component will be displayed in a 12-hour format with AM or PM appended at the end.

To instead display the time using a 24-hour format, you can use the ToString() method with the following syntax:

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

Here is what the various commands do:

  • yyyy: 4-digit year number
  • MM: 2-digit month number
  • dd: 2-digit day number
  • HH: 2-digit hours in 24-hour format
  • mm: 2-digit minutes
  • ss: 2-digit seconds
  • fff: 3-digit milliseconds

By using HH for the hours, we specify that we would like the time to be shown in a 24-hour format.

If we instead used hh, then the time would be shown in a 12-hour format.

The following example shows how to use this syntax in practice.

Example: Use Get-Date with 24-Hour Format in PowerShell

Suppose that we use the following syntax to get the current date and time with 6 hours added to it:

(Get-Date).AddHours(6)

The following screenshot shows how to use this syntax in practice:

 

This returns the following date and time:

  • Monday, April 22, 2024 2:34:07 PM

By default, the time is shown in a 12-hour format with PM appended at the end.

To instead display the time component using a 24-hour format, we can use the following syntax:

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

The following screenshot shows how to use this syntax in practice:

PowerShell Get-Date 24-hour format

This returns the following date and time:

  • 2024-04-22 14:34:32

Notice that the time is now shown using a 24-hour format.

Note that you could also use the following syntax to return only the time component:

(Get-Date).AddHours(6).ToString("HH:mm:ss") 

The following screenshot shows how to use this syntax in practice:

PowerShell Get-Date 24-hour time only

This returns the following time:

  • 14:34:53

Notice that this returns just the time component from the Get-Date cmdlet formatted using a 24-hour format.

Note: You can find the complete documentation for the Get-Date cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

How to Use Get-Date and Display Timezone in PowerShell
How to Compare Dates in PowerShell
How to Format a DateTime in PowerShell
How to Calculate Date Difference in PowerShell

Leave a Reply