44

For a check i need yesterday's date at 10:00pm in a variable.

I get yesterdays Date and current Time with

$a = (get-date).AddDays(-1)

But how do i manipulate the time to 22.00 and leave the variable still as Date-Object?

icnivad
  • 2,231
  • 8
  • 29
  • 35

8 Answers8

66

Use DateTime.Today as opposed to DateTime.Now (which is what Get-Date returns) because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond. (from masenkablast)

> [DateTime]::Today.AddDays(-1).AddHours(22)
Thursday, March 11, 2010 10:00:00 PM
Community
  • 1
  • 1
James Kolpack
  • 9,331
  • 2
  • 44
  • 59
  • 3
    wow I have this long complicated function in one of my scripts that does what this 1 line does. Yay for stupidity on my part. – Buddy Lindsey Jun 02 '10 at 02:20
18

I see this topic, but in my case I was looking for a way to improve the format. Using UFormat and adding -1 day

(Get-Date (Get-Date).addDays(-1) -UFormat "%Y%m%d-%H%M")
xjcl
  • 12,848
  • 6
  • 67
  • 89
javier
  • 191
  • 1
  • 2
6
(Get-Date (Get-Date -Format d)).AddHours(-2)
John Conde
  • 217,595
  • 99
  • 455
  • 496
Kevin
  • 61
  • 1
  • 1
5

I saw in at least one other place that people don't realize Date-Time takes in times as well, so I figured I'd share it here since it's really short to do so:

Get-Date # Following the OP's example, let's say it's Friday, March 12, 2010 9:00:00 AM
(Get-Date '22:00').AddDays(-1) # Thursday, March 11, 2010 10:00:00 PM

It's also the shortest way to strip time information and still use other parameters of Get-Date. For instance you can get seconds since 1970 this way (Unix timestamp):

Get-Date '0:00' -u '%s' # 1268352000

Or you can get an ISO 8601 timestamp:

Get-Date '0:00' -f 's' # 2010-03-12T00:00:00

Then again if you reverse the operands, it gives you a little more freedom with formatting with any date object:

'The sortable timestamp: {0:s}Z{1}Vs measly human format: {0:D}' -f (Get-Date '0:00'), "`r`n"
# The sortable timestamp: 2010-03-12T00:00:00Z
# Vs measly human format: Friday, March 12, 2010

However if you wanted to both format a Unix timestamp (via -u aka -UFormat), you'll need to do it separately. Here's an example of that:

'ISO 8601: {0:s}Z{1}Unix: {2}' -f (Get-Date '0:00'), "`r`n", (Get-Date '0:00' -u '%s')
# ISO 8601: 2010-03-12T00:00:00Z
# Unix: 1268352000

Hope this helps!

Pluto
  • 2,900
  • 27
  • 38
4

Format in other syntax is possible in this way

[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")

3

When I was to get yesterday with just the date in the format Year/Month/Day I use:

$Variable = Get-Date((get-date ).AddDays(-1))  -Format "yyyy-MM-dd"
fcdt
  • 2,371
  • 5
  • 14
  • 26
ClintR
  • 31
  • 1
2

Yet another way to do this:

(Get-Date).AddDays(-1).Date.AddHours(22)
0

Another possible method but Unix timestamp

 ([int64](Get-Date -UFormat %s) - [int64](New-TimeSpan -Hours 1).TotalSeconds)
Mike
  • 179
  • 1
  • 1
  • 10