Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

getQuarter

Returns the quarter (1–4) of the given date.

TypeScript
Copied!
1/**
2 * Returns the quarter (1–4) of the given date.
3 *
4 * @param date - The date to evaluate.
5 * @returns A number representing the quarter (1 to 4).
6 *
7 * @example
8 * getQuarter(new Date('2024-02-15')) // 1
9 * getQuarter(new Date('2024-06-01')) // 2
10 */
11export function getQuarter(date: Date): number {
12  return Math.floor(date.getMonth() / 3) + 1;
13}
  • Simple and Efficient

    Uses a minimal and performant formula without branching or complex logic.

  • Immutable Behavior

    Does not modify the original Date object, ensuring safe reuse.

  • Consistent Output

    Always returns a number between 1 and 4, making downstream logic predictable.

  • Well-Aligned with Financial and Reporting Calendars

    Maps directly to standard quarterly periods used in business and analytics.

Tests | Examples

TypeScript
Copied!
1test('returns Q1 for January', () => {
2  expect(getQuarter(new Date('2024-01-01'))).toBe(1);
3});
4
5test('returns Q2 for May', () => {
6  expect(getQuarter(new Date('2024-05-10'))).toBe(2);
7});
8
9test('returns Q3 for August', () => {
10  expect(getQuarter(new Date('2024-08-20'))).toBe(3);
11});
12
13test('returns Q4 for December', () => {
14  expect(getQuarter(new Date('2024-12-25'))).toBe(4);
15});

Common Use Cases

  • Financial Reporting

    Determine which quarter a transaction or record falls into for fiscal summaries.

  • Analytics and Dashboards

    Group data by quarter in charts, trends, or KPIs.

  • Date-Based Filtering

    Enable quarter-based filters in search interfaces or forms.

  • Content Scheduling

    Schedule or label content based on quarterly publication cycles.

Codebase: Utilities -> Dates -> getQuarter | Yevhen Klymentiev