How to Use Date in PowerShell: Syntax and Examples
In PowerShell, you use the
Get-Date cmdlet to get the current date and time or create specific date objects. You can format dates with -Format and perform date arithmetic using .NET date methods.Syntax
The basic syntax to get the current date and time is Get-Date. You can format the output using -Format followed by a format string. To create a specific date, use [datetime]::new(year, month, day).
- Get-Date: Returns current date and time.
- -Format: Specifies the output format.
- [datetime]::new(): Creates a custom date object.
powershell
Get-Date Get-Date -Format "yyyy-MM-dd" [datetime]::new(2024, 6, 15)
Output
Monday, June 10, 2024 10:00:00 AM
2024-06-10
Saturday, June 15, 2024 12:00:00 AM
Example
This example shows how to get the current date, format it as a short date, and add 7 days to the current date.
powershell
$currentDate = Get-Date $shortDate = Get-Date -Format 'MM/dd/yyyy' $futureDate = $currentDate.AddDays(7) Write-Output "Current Date: $currentDate" Write-Output "Formatted Date: $shortDate" Write-Output "Date After 7 Days: $futureDate"
Output
Current Date: Monday, June 10, 2024 10:00:00 AM
Formatted Date: 06/10/2024
Date After 7 Days: Monday, June 17, 2024 10:00:00 AM
Common Pitfalls
One common mistake is trying to format a date by converting it to a string and then back to a date, which can cause errors. Also, forgetting that Get-Date returns the current time including hours, minutes, and seconds can lead to unexpected results when comparing dates.
Always use date methods like AddDays() for arithmetic and -Format for display formatting.
powershell
# Wrong: converting formatted string back to date $dateString = (Get-Date -Format 'yyyy-MM-dd') # This is a string, not a date object # Right: use date object directly $date = Get-Date $newDate = $date.AddDays(5) Write-Output $newDate
Output
Monday, June 15, 2024 10:00:00 AM
Quick Reference
| Command | Description |
|---|---|
| Get-Date | Gets the current date and time |
| Get-Date -Format "formatString" | Formats the date output |
| [datetime]::new(year, month, day) | Creates a specific date object |
| $date.AddDays(n) | Adds n days to a date |
| $date.AddHours(n) | Adds n hours to a date |
Key Takeaways
Use Get-Date to get the current date and time in PowerShell.
Format dates for display using the -Format parameter with Get-Date.
Perform date math using methods like AddDays() on date objects.
Avoid converting formatted date strings back to dates; keep them as date objects.
Create specific dates using [datetime]::new(year, month, day).