Calculating the Quarter
Quick post since it’s been awhile since I’ve done anything. I’ve mentioned before but I do a lot of reports, and I recently got one to do some calculations for 95th percentile–well, kind of. The funny thing was the person who asked me was supposed to be making a solution themselves, kind of homework from the boss but they didn’t mention it to me and I thought it would be a fun challenge so I went and wrote up a script that could do it, parameters and everything. Oops! Anyway, when done they loved the report so I streamlined it from taking 10 minutes to run to about 1 or 2 (all in SQL, no PowerShell) and thought I was done with it. Then came the ask, not only do they want that data for the month, they want it for the whole quarter! So now I had to figure out which quarter I was in and what the date range for that would be. Yeah, I could put it in by hand, but there’s no challenge in that.
First came a Google to see if someone could do it in a one liner, and sure enough Vinoth over at StackOverflow had some great maths for that. Now calculate the dates and the easiest way was to simply create a little loop 1 through 4 and calculate my dates:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Define Quarters | |
$Quarters = @{} | |
$Start = Get-Date –Month 1 –Date 1 –Year (Get-Date).Year | |
ForEach ($Q in (1..4)) | |
{ | |
$Quarters.Add($Q,[PSCustomObject]@{ | |
From = $Start | |
To = $Start.AddMonths(3).AddTicks(-1) | |
}) | |
$Start = $Start.AddMonths(3) | |
} | |
#Define this quarter | |
$Quarter = [int]([math]::Ceiling((Get-Date –Format MM)/3)) |
First use Get-Date to get the January 1st, then loop 4 times adding 3 months each time to get the date ranges. Now to get a date range for the current quarter? $Quarters[$Quarter].
Thank you