Josh Nelson
Josh Nelson

Reputation: 69

Today and Yesterday's date at midnight in specific format

I need to get today and yesterdays date at midnight in the following format:

08/05/2018 00:00

The best I seem to be able to get is this:

get-date -Uformat "%D %R" -Hour 0 -Minute 00

08/05/18 00:00

I fail miserably when trying to get yesterday at midnight.

(Get-Date -UFormat "%s" -Hour 0 -Minute 00 -Second 00).AddDays(-1)

Method invocation failed because [System.String] does not contain a method named AddDays. At line:1 char:1 + (Get-Date -UFormat "%s" -Hour 0 -Minute 00 -Second 00).AddDays(-1) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

Upvotes: 5

Views: 11551

Answers (5)

Patrick Burwell
Patrick Burwell

Reputation: 173

(Get-Date).AddDays(-1)|Get-Date -format "yyyyMMdd"

Upvotes: 0

user6811411
user6811411

Reputation:

To get a date(time) at midnight you can use :

(Get-Date).Date

Or

[datetime]::Today

To format it according to your requirement can be tricky if your current date format has a different separator (as is the case here).

> (get-date).Date.ToString('MM/dd/yyyy HH:mm')
08-05-2018 00:00

The .ToString() method overrides the separator; to take the slash literal you have to escape it with a backslash:

> (get-date).Date.ToString('MM\/dd\/yyyy HH:mm')
08/05/2018 00:00

Or use:

> (get-date).Date.ToString('MM/dd/yyyy HH:mm', [cultureinfo]::InvariantCulture)
08/05/2018 00:00

Upvotes: 6

Avshalom
Avshalom

Reputation: 8889

For today use [DateTime]::Today and format it with ToString()

[Datetime]::Today.ToString("dd/MM/yyyy HH:mm")

For Yesterday, just add AddDays(-1)

[Datetime]::Today.AddDays(-1).ToString("dd/MM/yyyy HH:mm")

Upvotes: 1

s.feradov
s.feradov

Reputation: 86

You were on the right track with the -UFormat option:

Get-Date -Hour 0 -Minute 00 -UFormat "%m/%d/%Y %H:%M"

This produces the following output:

08/05/2018 00:00

The error you are seeing is due to the fact that you are invoking AddDays method over a string. To manipulate the date, you can do the following:

(Get-Date -Hour 0 -Minute 00).AddDays(-1) | Get-Date -UFormat "%m/%d/%Y %H:%M"

This will produce the desired output.

Upvotes: 1

gvee
gvee

Reputation: 17161

Code

(Get-Date).ToString("dd/MM/yyyy 00:00")
(Get-Date).AddDays(-1).ToString("dd/MM/yyyy 00:00")

You have to perform the AddDays to the date while it's still a date (and not a string that looks like a date).

Result

05/08/2018 00:00
04/08/2018 00:00

For American format

dd/MM/yyyy simply becomes MM/dd/yyyy

Upvotes: 3

Related Questions