In PowerShell, you can format DateTime objects using various methods and format strings.
The following methods show how you can format DateTime in PowerShell.
Method 1: Using the Get-Date with the -Format parameter
$date = Get-Date -Format "dd-MM-yyyy HH:mm:ss"
$date
This example will output the current date in the specified format “dd-MM-yyyy HH:mm:ss“.
Method 2: Using the ToString() method with a custom format string
$date = (Get-Date).ToString("MM-dd-yyyy HH:mm:ss")
$date
This example outputs the current date in a custom format “MM-dd-yyyy HH:mm:ss“.
Method 3: Using the .NET format specifiers
$date = Get-Date -Format "d"
$date
This example outputs the current date and time in a specific format.
You can use the commonly used format specifiers.
yyyy
: Four-digit year.MM
: Two-digit month (01-12).dd
: Two-digit day (01-31).HH
: Two-digit hour (00-23).mm
: Two-digit minute (00-59).ss
: Two-digit second (00-59).
The following examples show how to format a DateTime object using the above methods.
Format DateTime Using Get-Date with the -Format Parameter
The following PowerShell script shows how to format a datetime object using Get-Date with the -Format parameter.
$date = Get-Date -Format "dd-MM-yyyy HH:mm:ss" $date
Output:

In the script, the Get-Date cmdlet with the -Format parameter specifies the “dd-MM-yyyy HH:mm:ss” format.
After running the script, this will output the current date and time in the format “dd-MM-yyyy HH:mm:ss“.
Format DateTime Using the ToString() method
You can use the ToString() method with a custom format string to format a DateTime object in PowerShell.
$date = (Get-Date).ToString("MM-dd-yyyy HH:mm:ss") $date
Output:

This will output the current date and time in the format: MM-dd-yyyy HH:mm:ss .
Format DateTime Using the .NET format Specifiers
Another way to format a DateTime object is to use the .NET format specifiers.
$date = Get-Date -Format "d" $date
Output:
4/17/2024
This will output the current date and time in the format: “MM/dd/YYYY” format.
Conclusion
I hope the above article on how to format a DateTime object in PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.