Getting Yesterday’s Date – at Midnight!

by Dec 26, 2013

Getting relative dates (like yesterday or one week ahead) is easy once you know the Add…() methods every DateTime object supports. This would give you yesterday:

$today = Get-Date
$yesterday = $today.AddDays(-1)

$yesterday will be exactly 24 hours before now. So what if you would like yesterday, but at a given time? Let's say, yesterday at midnight?

If you really want today at midnight, things are easy:

$todayMidnight = Get-Date -Hour 0 -Minute 0 -Second 0

And if you want another date with a given time, use Get-Date again to override the parts of the date you need. This is yesterday at midnight:

$today = Get-Date
$yesterday = $today.AddDays(-1)
$yesterday | Get-Date -Hour 0 -Minute 0 -Second 0 

Twitter This Tip! ReTweet this Tip!