Reputation: 23
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
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
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