Home > other >  Increment hours by 30 minutes 20 times in Powershell
Increment hours by 30 minutes 20 times in Powershell

Time:01-28

I have to create multiple job in my app. These jobs should be separated by 30 minutes apart starting at 17:00. My dilemma how to get 20 times in hour and minutes ( HH:MM) format starting at 17:00 ?? Onces i have those times , i can loop all jobs 30 minutes apart. Thank you

So far i have tried

$ts = New-TimeSpan -Hours 17 -Minutes 00

But adding minutes to $ts not working

PS F:\> $ts.AddMinutes(30)
Method invocation failed because [System.TimeSpan] does not contain a method named 'addminutes'.
At line:1 char:1
  $ts.AddMinutes(30)
  ~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      FullyQualifiedErrorId : MethodNotFound

CodePudding user response:

You can simply add a new timespan:

$newts = $ts   (New-TimeSpan -Minutes 30)

CodePudding user response:

Paolo's helpful answer shows how to add a timespan to an existing timespan, where the operation translates to the [timespan] type's .Add() method.

By contrast, it is the [datetime] / [datetimeoffset] types that have an .AddMinutes() .AddMinutes() method.

Therefore, you could do the following:

# Get today's date at 17:00 hours
$start = Get-Date -Hour 17 -Minute 0 -Second 0 -MilliSecond 0
# Loop 20 times and add 30 minutes each, and format as "HH:mm"
0..19 | ForEach-Object { $start.AddMinutes($_ * 30).ToString('HH:mm') }

Output:

17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
00:00
00:30
01:00
01:30
02:00
02:30

CodePudding user response:

You can add a string that will automatically convert to type [timespan], since the left argument is [timespan]:

$ts = [timespan]'17:30'
$ts  = '0:30'
$ts

Days              : 0
Hours             : 18
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 648000000000
TotalDays         : 0.75
TotalHours        : 18
TotalMinutes      : 1080
TotalSeconds      : 64800
TotalMilliseconds : 64800000
  • Related