How to Create a DateTime Object in PowerShell (With Examples)


You can use the following methods to create a datetime object in PowerShell:

Method 1: Create DateTime Object with Current Date & Time

$my_dt = Get-Date

This particular example creates a variable named $my_dt that contains the current date and time.

Method 2: Create DateTime Object with Specific Date & Time

$my_dt = (Get-Date -Date "2024-01-25 00:00:00Z").ToUniversalTime()

This particular example creates a variable named $my_dt that contains the date January 25, 2024.

Note that we use ToUniversalTime() to display the specific date in universal time rather than in the local time zone of your computer.

The following examples show how to use each method in practice.

Example 1: Create DateTime Object with Current Date & Time in PowerShell

We can use the following syntax in PowerShell to create a DateTime object named $my_dt that contains the current date and time:

$my_dt = Get-Date

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

Notice that when we print $my_dt we can see that it contains the following date and time:

  • Monday, June 17, 2024 11:21:23 AM

This represents the current date and time when this article is being written.

Example 2: Create DateTime Object with Specific Date & Time in PowerShell

We can use the following syntax in PowerShell to create a DateTime object named $my_dt that contains the specific date January 25, 2024:

$my_dt = (Get-Date -Date "2024-01-25 00:00:00Z").ToUniversalTime()

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

PowerShell create datetime object with specific time

Notice that when we print $my_dt we can see that it contains the following date and time:

  • Thursday, January 25, 2024 12:00:00 AM

This represents the date that we specified by using the -Date operator with the Get-Date cmdlet.

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