Skip to main content

How to Format a DateTime in PowerShell

3 min read
powershell datetime format date string

In PowerShell, you can format DateTime objects using various methods and format strings.

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.

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).

Format DateTime Using Get-Date with the -Format Parameter

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.

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.

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.


Date & Time Operations

File Date Operations

String Operations

Data Processing & Selection

Variables & Storage

File Operations

Control Flow & Logic

Data Export & Conversion

Functions & Organization

System Operations

Comprehensive Guides