Difference between dates using PowerShell

Where is the $endFromDatabase variable coming from? That part isn't clear in your post.

To demonstrate subtracting DateTime objects, see the example below.

$TimeSpan = [DateTime]'2014-01-10' - [DateTime]'2014-01-06';

You will receive a System.TimeSpan as a result from the operation, so you can explore members such as:

$TimeSpan.TotalDays;

My guess is that you just need to fix the value in the $endFromDatabase variable, so that it can be cast into a System.DateTime object.

Background

Subtracting a [DateTime] object from another [DateTime] object works, because the [DateTime] class overloads the subtraction operator, which results in the op_subtraction Intermediate Language (IL) method. You can examine this in a .NET object explorer tool, such as .NET Reflector.

You'll notice that there is a second overload of the subtraction operator, which allows you to subtract a [TimeSpan] object from a [DateTime] object.

.NET Reflector Screenshot


Something like this?

$begin = [datetime]'02/10/2011'
$end   = [datetime]'01/10/2013'

$monthdiff = $end.month - $begin.month + (($end.Year - $begin.year) * 12)
$monthdiff

23

Tags:

Powershell