The Surly Admin

Father, husband, IT Pro, cancer survivor

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:


#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))

view raw

Get-Quarter.ps1

hosted with ❤ by GitHub

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].

 

Advertisement

November 15, 2016 - Posted by | PowerShell | ,

1 Comment »

  1. Thank you

    Comment by Sagar S | April 3, 2019 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: