How to Calculate Date Differences in PowerShell
Are you new to PowerShell and need to work with dates? Don't worry! In this post, I'll show you some simple ways to calculate the difference between dates using PowerShell. Whether you're tracking project timelines or calculating ages, these methods will help you get started.
The Basics: Simple Date Subtraction
The easiest way to find the difference between two dates is by using simple subtraction. Here's how:
$date1 = Get-Date "2025-01-01"
$date2 = Get-Date "2025-03-15"
$difference = $date2 - $date1
PowerShell does all the heavy lifting for you. To see how many days are between these dates, just use:
$difference.Days
A Cleaner Approach
There's an even cleaner way to do this using the New-TimeSpan cmdlet:
New-TimeSpan -Start "2025-01-01" -End "2025-03-15"
This method is great because it's more readable and straightforward. Want just the days? Add .Days at the end:
(New-TimeSpan -Start "2025-01-01" -End "2025-03-15").Days
Working with Today's Date
Need to know how many days since or until a specific date? Use Get-Date:
# Days since January 1, 2025
(New-TimeSpan -Start "2025-01-01" -End (Get-Date)).Days
# Days until December 31, 2025
(New-TimeSpan -Start (Get-Date) -End "2025-12-31").Days
Pro Tip: Different Date Formats
If you're working with dates in different formats (like DD/MM/YYYY), here's how to handle them:
$date1 = [DateTime]::ParseExact("01/01/2025", "dd/MM/yyyy", $null)
$date2 = [DateTime]::ParseExact("15/03/2025", "dd/MM/yyyy", $null)
($date2 - $date1).Days
Date calculations in PowerShell don't have to be complicated! Start with the simple subtraction method, and as you get more comfortable, try out New-TimeSpan for cleaner code. Remember, PowerShell is here to make your life easier, not harder.
Try these examples in your PowerShell console and experiment with different dates. The more you practice, the more natural it will become.
Happy coding!
About this post
Posted: 2025-09-04
By: dwirch
Viewed: 3,507 times
Categories
Scripting
Powershell
Beginners Guides
Attachments
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.