Time to the nearest 15 min interval

This is the code I am using to round the Date to 15-minute interval (00,15,30,45)
But is as you can see from the example it only rounds down
How can I fix this so it rounds to The actual nearest 15 minutes instead of just rounding it down?

{$TodayDate = Get-Date -Date "6/25/2019 12:46:22"}
{$TodayDate = Get-Date -Date "25/06/2019 12:46:22"}

$Date1 = $TodayDate
$Date2 = $TodayDate.AddMinutes(-2)
Write-Host "Actual Date: $Date1"
Write-Host "Rounded Date: $($Date1.AddMinutes(- $Date1.Minute % 15 ))"
Write-Host "Actual Date: $Date2"
Write-Host "Rounded Date: $($Date2.AddMinutes(- $Date2.Minute % 15 ))"

Actual Date: 06/25/2019 12:46:22
Rounded Date: 06/25/2019 12:45:22

Actual Date: 06/25/2019 12:44:22
Rounded Date: 06/25/2019 12:30:22

Something like this should work actually ā€¦

$FifteenMinutes = (New-TimeSpan -Minutes 15 ).Ticks
$Date = Get-Date
$Ticks = ([Math]::Round($Date.Ticks / $FifteenMinutes, 0) * $FifteenMinutes) -as [long]

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to help you making their work twice or more.


1 Like

Thanks, Olaf
Your solution works!

Thanks for confirmation. Iā€™m glad it helped. :+1:t4: :wink: