How to Format a DateTime in PowerShell (With Examples)


The easiest way to format a datetime in PowerShell is to use the ToString() method.

Here is the basic syntax you can use:

$mydate = Get-Date

$mydate.ToString("MM/dd/yyyy")

This particular example uses Get-Date to save the current date and time in a variable named $mydate, then uses ToString() to format the date using a MM/dd/yyyy format.

Note that you can use the following specifiers to format the date exactly how you would like:

  • dd: 2 digit day of the month
  • MM: 2 digit month number
  • YY: 2 digit year number
  • dddd: Full name of day
  • MMMM: Full name of month
  • yyyy: 4 digit year number
  • HH:mm: Time in 24-hour format
  • HH:mm:ss: Time in 24-hour format with seconds
  • HH:mm:ss.fff: Time in 24-hour format with milliseconds
  • hh:mm: Time in 12-hour format
  • hh:mm tt: Time in 12-hour format with AM/PM

The following examples show how to use some of these formats in practice:

Example 1: Format DateTime Using MM/dd/yyyy

We can use the following syntax to format a datetime using MM/dd/yyyy as the format:

$mydate = Get-Date

$mydate.ToString("MM/dd/yyyy")

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

Format DateTime in PowerShell

Notice that the datetime is formatted as 03/01/2024.

Example 2: Format DateTime Using MM/dd/yyyy HH:mm:ss

We can use the following syntax to format a datetime using MM/dd/yyyy HH:mm:ss as the format:

$mydate = Get-Date

$mydate.ToString("MM/dd/yyyy HH:mm:ss")

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

Notice that the datetime is formatted as 03/01/2024 08:38:10.

Example 3: Format DateTime Using MM/dd/yyyy hh:mm tt

We can use the following syntax to format a datetime using MM/dd/yyyy hh:mm tt as the format:

$mydate = Get-Date

$mydate.ToString("MM/dd/yyyy hh:mm tt")

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

PowerShell format datetime with AM / PM

Notice that the datetime is formatted as 03/01/2024 08:40 AM.

By using the tt specifier, we are able to add the AM / PM distinction at the end of the datetime.

Note: In this tutorial we only illustrated a few examples of how to format datetimes in PowerShell. Feel free to use any combination of specifiers you would like to format your datetime in the exact way you want.

Related Tutorials

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

PowerShell: How to Compare Dates
PowerShell: How to List Files in Directory by Date
PowerShell: Get List of Files Modified After Certain Date
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply