# Time series

Time dimensions, the timestamp format, missing periods and the granularity picker.

The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).

Give a dimension `type: 'time'` and set `granularity` on the dimension itself. The chart then formats the dates for that granularity, puts the rows in date order and adds the periods that have no row.

## A time dimension

Four weeks of signups, with one week missing from the rows.

```tsx title="SignupsByWeek.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';

const week = dimension({ name: 'week', title: 'Week', type: 'time', granularity: 'week' });
const signups = measure({ name: 'signups', title: 'Signups' });

// Each value is the start of its week (a Monday). There is no row for the
// week of 19 January, so the chart adds that week itself and leaves it empty.
const rows = [
  { week: '2026-01-05T00:00:00.000', signups: 212 },
  { week: '2026-01-12T00:00:00.000', signups: 248 },
  { week: '2026-01-26T00:00:00.000', signups: 231 },
  { week: '2026-02-02T00:00:00.000', signups: 274 },
];

export function SignupsByWeek() {
  return (
    <div style={{ height: 320 }}>
      <BarChart
        title="Signups per week"
        dimension={week}
        measures={[signups]}
        results={results(rows)}
      />
    </div>
  );
}
```

Result: five weeks on the axis, with no bar for the week of 19 January.

## Time values

A time value has to be:

- **A string in the form `YYYY-MM-DDTHH:mm:ss.SSS`**, with no `Z` and no offset. Anything else is shown as raw text.
- **The start of its period**: the first of the month for `month`, the Monday for `week`. A row at any other time is left off the chart.
- **Under the dimension’s `name`** in each row.

The time zone used to work out date ranges comes from the provider: see [Localisation](/docs/localisation.md).

## Missing periods

Periods with no row are added between your first and last row, so a gap in the data shows as a gap. Set `dateBounds` to extend the axis past your rows, or `ignoreEmptyDate` to leave empty periods out: both are [field options](/docs/describing-your-data.md#field-options).

## Let readers change the granularity

Turn on `showGranularityDropdown`, keep the granularity in state and pass `setGranularity`. The card shows a picker from day to year. The chart does not re-bucket your rows: you query again at the new granularity.

```tsx title="OrdersOverTime.tsx"
import { useState } from 'react';
import { LineChart, dimension, measure, results } from 'em-kit';
import type { Granularity } from 'em-kit';

const orders = measure({ name: 'orders', title: 'Orders' });

export function OrdersOverTime() {
  const [granularity, setGranularity] = useState<Granularity>('month');

  const orderedAt = dimension({
    name: 'ordered_at',
    title: 'Order date',
    type: 'time',
    granularity,
    inputs: { showGranularityDropdown: true }, // shows the picker
  });

  return (
    <div style={{ height: 400 }}>
      <LineChart
        title="Orders"
        xAxis={orderedAt}
        measures={[orders]}
        results={results(ordersBy(granularity))} // query again at the new granularity
        granularity={granularity} // the granularity of the rows, as on the dimension
        setGranularity={setGranularity} // called with the reader's choice
        showValueLabels={false}
      />
    </div>
  );
}

// Stand-in for your API: a year of daily orders, summed into the
// requested buckets. Each bucket is keyed by the start of its period.
const days = Array.from({ length: 365 }, (_, i) => ({
  date: new Date(Date.UTC(2025, 0, 1 + i)),
  orders: 40 + Math.round(i / 9) + ((i * 37) % 23),
}));

const startOf = (date: Date, granularity: Granularity) => {
  const [y, m, d] = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()];
  if (granularity === 'year') return Date.UTC(y, 0, 1);
  if (granularity === 'quarter') return Date.UTC(y, m - (m % 3), 1);
  if (granularity === 'month') return Date.UTC(y, m, 1);
  if (granularity === 'week') return Date.UTC(y, m, d - ((date.getUTCDay() + 6) % 7));
  return Date.UTC(y, m, d);
};

function ordersBy(granularity: Granularity) {
  const totals = new Map<number, number>();
  for (const day of days) {
    const start = startOf(day.date, granularity);
    totals.set(start, (totals.get(start) ?? 0) + day.orders);
  }
  return [...totals].map(([start, total]) => ({
    ordered_at: new Date(start).toISOString().slice(0, 23), // drop the "Z"
    orders: total,
  }));
}
```

Result: a line of monthly totals and a picker set to Month. Choosing Week redraws the line with weekly totals.

## Time as the grouping field

One case needs a second key. When a time dimension is the `groupBy` of a stacked or grouped bar chart, or the point or group field of a scatter or bubble chart, the chart reads it from the key `name.granularity`, for example `month.month`.

```tsx title="RevenueByPlanAndMonth.tsx"
import { BarChartStacked, dimension, measure, results } from 'em-kit';

const plan = dimension({ name: 'plan', title: 'Plan' });
const month = dimension({ name: 'month', title: 'Month', type: 'time', granularity: 'month' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });

const january = '2026-01-01T00:00:00.000';
const february = '2026-02-01T00:00:00.000';

// The month is the grouping field, so each row also has it under "month.month".
const rows = [
  { plan: 'Starter', month: january, 'month.month': january, revenue: 18400 },
  { plan: 'Starter', month: february, 'month.month': february, revenue: 21700 },
  { plan: 'Growth', month: january, 'month.month': january, revenue: 42900 },
  { plan: 'Growth', month: february, 'month.month': february, revenue: 47300 },
];

export function RevenueByPlanAndMonth() {
  return (
    <div style={{ height: 320 }}>
      <BarChartStacked
        title="Revenue by plan, split by month"
        xAxis={plan}
        groupBy={month}
        measure={revenue}
        results={results(rows)}
      />
    </div>
  );
}
```

Result: one stacked bar per plan, with a segment and a legend entry for each month.
