Jason Warren
Jason Warren

Reputation: 23

Subtracting time in powershell

I use the following time code:

$time = [DateTime]::UtcNow | get-date -Format "yyyyMMddHH"
$m2=$time-02  # trying to subtract 2 hours

However, for times like 2021021701, subtracting 2 gives me 2021021699. How can I have the time display in the correctly?

Upvotes: 2

Views: 4090

Answers (2)

js2010
js2010

Reputation: 27606

Another way. The 2nd arg can be a datetime or a timespan. $time is a datetime.

$time = get-date 
$m2 = $time - [timespan]'2:0'
$m2

Wednesday, February 17, 2021 7:31:59 PM

Upvotes: 2

mklement0
mklement0

Reputation: 440317

To perform date calculations, operate on [datetime] (System.DateTime) instances and use that type's methods, such as .AddHours(); only after that should you create the desired string representation:

# Get the current UTC time as a [datetime] instance.
$time = [DateTime]::UtcNow

# Subtract 2 hours.
$m2Time = $time.AddHours(-2)

# Create the desired string representation.
$m2 = Get-Date $m2Time -Format 'yyyyMMddHH'

Upvotes: 1

Related Questions