Date arithmetic within PowerShell

Overview

There are many ways to do date arithmetic within PowerShell. This article gives a few examples.

Example 1

In this example we’re subtracting one date from another to give the difference in days between the two dates.

$today = Get-Date;
#
$futureDate=[datetime]"2012-06-16" # The ISO 8601 notation of YYYY-MM-DD
#or
# Parameters:
# year - The year (1 through 9999).
# month - The month (1 through 12).
# day - The day (1 through the number of days in month).
#$futureDate = New-Object System.DateTime(2012, 06, 16); # year, month, day

$tspan=New-TimeSpan $today $futureDate;
$diffDays=($tspan).days;

Write-Host "Todays date = " ("{0:f}" -f $today);
Write-Host "The future date = " ("{0:f}" -f $futureDate);
Write-Host "The difference in days is $diffDays";

Example 2

Adding or subtracting a number of days from the current date. It doesn’t have to be the current date, we could carry out these actions on other predetermined dates.

Adding a number of days. The variable numberOfDays is the number of days we wish to add.

[DateTime]::Now.Add([TimeSpan]::FromDays($numberOfDays))

Subtracting a number days. Again, the variable numberOfDays is the number of days we wish to subtract.

[DateTime]::Now.Subtract([TimeSpan]::FromDays($numberOfDays))

See also

The Wonders of Date Math using Windows PowerShell

Reference

Using the New-Timespan Cmdlet The New-TimeSpan cmdlet provides a way to do date arithmetic within Windows PowerShell.

DateTime Structure Represents an instant in time, typically expressed as a date and time of day.

Numeric representation of dates and time

ISO 8601:2004 is applicable whenever representation of dates in the Gregorian calendar, times in the 24-hour timekeeping system, time intervals and recurring time intervals or of the formats of these representations are included in information interchange.

This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s