0
# Time Operations
1
2
Vega's time processing system provides comprehensive temporal data handling with time intervals, binning, formatting, sequence generation, and calendar calculations for time-based visualizations.
3
4
## Capabilities
5
6
### Time Constants
7
8
Standard time unit definitions and identifiers.
9
10
```typescript { .api }
11
/** Registry of all available time units */
12
const TIME_UNITS: {
13
year: 'year';
14
quarter: 'quarter';
15
month: 'month';
16
week: 'week';
17
date: 'date';
18
day: 'day';
19
dayofyear: 'dayofyear';
20
hours: 'hours';
21
minutes: 'minutes';
22
seconds: 'seconds';
23
milliseconds: 'milliseconds';
24
};
25
26
/** Year time unit constant */
27
const YEAR: 'year';
28
29
/** Quarter time unit constant */
30
const QUARTER: 'quarter';
31
32
/** Month time unit constant */
33
const MONTH: 'month';
34
35
/** Week time unit constant */
36
const WEEK: 'week';
37
38
/** Date (day of month) time unit constant */
39
const DATE: 'date';
40
41
/** Day of week time unit constant */
42
const DAY: 'day';
43
44
/** Day of year time unit constant */
45
const DAYOFYEAR: 'dayofyear';
46
47
/** Hours time unit constant */
48
const HOURS: 'hours';
49
50
/** Minutes time unit constant */
51
const MINUTES: 'minutes';
52
53
/** Seconds time unit constant */
54
const SECONDS: 'seconds';
55
56
/** Milliseconds time unit constant */
57
const MILLISECONDS: 'milliseconds';
58
59
type TimeUnit = 'year' | 'quarter' | 'month' | 'week' | 'date' | 'day' | 'dayofyear' | 'hours' | 'minutes' | 'seconds' | 'milliseconds';
60
```
61
62
### Time Unit Operations
63
64
Time unit specification and utility functions.
65
66
```typescript { .api }
67
/**
68
* Get time unit specifier string for formatting
69
* @param units - Time units array or single unit
70
* @returns Format specifier string
71
*/
72
function timeUnitSpecifier(units: TimeUnit[] | TimeUnit): string;
73
74
/**
75
* Get all available time units
76
* @returns Array of time unit identifiers
77
*/
78
function timeUnits(): TimeUnit[];
79
80
/**
81
* Calculate day of year for a date
82
* @param date - Date object
83
* @returns Day of year (1-366)
84
*/
85
function dayofyear(date: Date): number;
86
87
/**
88
* Calculate week number for a date
89
* @param date - Date object
90
* @returns Week number
91
*/
92
function week(date: Date): number;
93
94
/**
95
* Calculate day of year for a UTC date
96
* @param date - Date object
97
* @returns UTC day of year (1-366)
98
*/
99
function utcdayofyear(date: Date): number;
100
101
/**
102
* Calculate UTC week number for a date
103
* @param date - Date object
104
* @returns UTC week number
105
*/
106
function utcweek(date: Date): number;
107
108
/**
109
* Calculate quarter for a date
110
* @param date - Date object
111
* @returns Quarter number (1-4)
112
*/
113
function quarter(date: Date): number;
114
115
/**
116
* Calculate UTC quarter for a date
117
* @param date - Date object
118
* @returns UTC quarter number (1-4)
119
*/
120
function utcquarter(date: Date): number;
121
```
122
123
### Time Intervals
124
125
Time interval creation and manipulation.
126
127
```typescript { .api }
128
/**
129
* Create a time interval for the specified unit
130
* @param unit - Time unit identifier
131
* @returns Time interval object
132
*/
133
function timeInterval(unit: TimeUnit): TimeInterval;
134
135
/**
136
* Create UTC time interval for the specified unit
137
* @param unit - Time unit identifier
138
* @returns UTC time interval object
139
*/
140
function utcInterval(unit: TimeUnit): TimeInterval;
141
142
/**
143
* Calculate time offset for interval arithmetic
144
* @param unit - Time unit identifier
145
* @param step - Number of units to offset
146
* @returns Time offset function
147
*/
148
function timeOffset(unit: TimeUnit, step?: number): (date: Date) => Date;
149
150
/**
151
* Calculate UTC time offset for interval arithmetic
152
* @param unit - Time unit identifier
153
* @param step - Number of units to offset
154
* @returns UTC time offset function
155
*/
156
function utcOffset(unit: TimeUnit, step?: number): (date: Date) => Date;
157
158
/**
159
* Generate sequence of dates at regular intervals
160
* @param start - Start date
161
* @param stop - End date
162
* @param step - Time interval or step count
163
* @returns Array of dates
164
*/
165
function timeSequence(start: Date, stop: Date, step: TimeInterval | number): Date[];
166
167
/**
168
* Generate UTC sequence of dates at regular intervals
169
* @param start - Start date
170
* @param stop - End date
171
* @param step - Time interval or step count
172
* @returns Array of UTC dates
173
*/
174
function utcSequence(start: Date, stop: Date, step: TimeInterval | number): Date[];
175
176
interface TimeInterval {
177
/** Floor date to interval boundary */
178
floor(date: Date): Date;
179
180
/** Ceil date to interval boundary */
181
ceil(date: Date): Date;
182
183
/** Round date to nearest interval boundary */
184
round(date: Date): Date;
185
186
/** Offset date by specified number of intervals */
187
offset(date: Date, step?: number): Date;
188
189
/** Generate range of dates */
190
range(start: Date, stop: Date, step?: number): Date[];
191
192
/** Filter dates that match interval */
193
filter(test: (date: Date) => boolean): TimeInterval;
194
195
/** Create interval with different step size */
196
every(step: number): TimeInterval;
197
198
/** Count intervals between two dates */
199
count(start: Date, end: Date): number;
200
}
201
```
202
203
### Time Flooring
204
205
Date flooring operations for time alignment.
206
207
```typescript { .api }
208
/**
209
* Floor date to time unit boundary
210
* @param unit - Time unit for flooring
211
* @returns Date flooring function
212
*/
213
function timeFloor(unit: TimeUnit): (date: Date) => Date;
214
215
/**
216
* Floor date to UTC time unit boundary
217
* @param unit - Time unit for flooring
218
* @returns UTC date flooring function
219
*/
220
function utcFloor(unit: TimeUnit): (date: Date) => Date;
221
```
222
223
### Time Binning
224
225
Time-based data binning for temporal aggregation.
226
227
```typescript { .api }
228
/**
229
* Create time binning function
230
* @param options - Time binning configuration
231
* @returns Time binning function
232
*/
233
function timeBin(options: TimeBinOptions): (date: Date) => Date;
234
235
interface TimeBinOptions {
236
/** Time unit for binning */
237
unit?: TimeUnit;
238
239
/** Step size for binning */
240
step?: number;
241
242
/** Use UTC time */
243
utc?: boolean;
244
245
/** Bin extent */
246
extent?: [Date, Date];
247
248
/** Maximum number of bins */
249
maxbins?: number;
250
251
/** Bin boundaries */
252
anchor?: Date;
253
254
/** Nice bin boundaries */
255
nice?: boolean;
256
}
257
258
interface TimeBin {
259
/** Bin start time */
260
start: Date;
261
262
/** Bin end time */
263
end: Date;
264
265
/** Bin step interval */
266
step: TimeInterval;
267
268
/** Bin unit */
269
unit: TimeUnit;
270
}
271
```
272
273
## Time Scale Integration
274
275
### Time Scale Support
276
277
Time scales work seamlessly with time operations for temporal visualizations.
278
279
```typescript { .api }
280
/** Time scale configuration for temporal data mapping */
281
interface TimeScaleConfig {
282
/** Scale type */
283
type: 'time' | 'utc';
284
285
/** Time domain */
286
domain: Date[] | TimeScaleDomain;
287
288
/** Output range */
289
range: any[];
290
291
/** Nice domain boundaries */
292
nice?: TimeUnit | TimeInterval | boolean;
293
294
/** Clamp values to domain */
295
clamp?: boolean;
296
}
297
298
interface TimeScaleDomain {
299
/** Data source reference */
300
data: string;
301
302
/** Date field reference */
303
field: string;
304
305
/** Sort configuration */
306
sort?: boolean;
307
}
308
```
309
310
## Usage Examples
311
312
### Basic Time Operations
313
314
```typescript
315
import {
316
timeInterval,
317
timeFloor,
318
timeSequence,
319
dayofyear,
320
quarter
321
} from "vega";
322
323
const date = new Date('2023-06-15T14:30:00');
324
325
// Floor to different time units
326
const dayFloor = timeFloor('day');
327
const monthFloor = timeFloor('month');
328
329
console.log(dayFloor(date)); // 2023-06-15T00:00:00
330
console.log(monthFloor(date)); // 2023-06-01T00:00:00
331
332
// Calculate time properties
333
console.log(dayofyear(date)); // 166
334
console.log(quarter(date)); // 2
335
```
336
337
### Time Intervals
338
339
```typescript
340
import { timeInterval, timeOffset } from "vega";
341
342
// Create monthly interval
343
const monthly = timeInterval('month');
344
345
const startDate = new Date('2023-01-15');
346
347
// Floor to month boundary
348
const monthStart = monthly.floor(startDate); // 2023-01-01
349
350
// Generate monthly sequence
351
const months = monthly.range(
352
new Date('2023-01-01'),
353
new Date('2023-12-31'),
354
1
355
);
356
console.log(months.length); // 12 months
357
358
// Offset operations
359
const offset = timeOffset('month', 3);
360
const futureDate = offset(startDate); // 3 months later
361
```
362
363
### Time Binning
364
365
```typescript
366
import { timeBin } from "vega";
367
368
const data = [
369
new Date('2023-01-15T08:30:00'),
370
new Date('2023-01-15T14:45:00'),
371
new Date('2023-01-15T20:15:00'),
372
new Date('2023-01-16T09:00:00')
373
];
374
375
// Create hourly bins
376
const hourlyBin = timeBin({
377
unit: 'hours',
378
step: 4,
379
nice: true
380
});
381
382
const bins = data.map(date => ({
383
original: date,
384
binned: hourlyBin(date)
385
}));
386
387
console.log(bins);
388
// Groups times into 4-hour bins
389
```
390
391
### Time Sequences
392
393
```typescript
394
import { timeSequence, utcSequence } from "vega";
395
396
const start = new Date('2023-01-01');
397
const end = new Date('2023-01-31');
398
399
// Generate daily sequence
400
const dailySequence = timeSequence(start, end, timeInterval('day'));
401
console.log(dailySequence.length); // 31 days
402
403
// Generate weekly sequence
404
const weeklySequence = timeSequence(start, end, timeInterval('week'));
405
console.log(weeklySequence.length); // ~4-5 weeks
406
407
// UTC sequences for consistent timezone handling
408
const utcDaily = utcSequence(start, end, timeInterval('day'));
409
```
410
411
### Time Unit Specifiers
412
413
```typescript
414
import { timeUnitSpecifier, timeUnits } from "vega";
415
416
// Get format specifiers for time units
417
const yearSpec = timeUnitSpecifier('year'); // '%Y'
418
const monthDaySpec = timeUnitSpecifier(['month', 'date']); // '%b %d'
419
const timeSpec = timeUnitSpecifier(['hours', 'minutes']); // '%H:%M'
420
421
// Get all available time units
422
const allUnits = timeUnits();
423
console.log(allUnits); // ['year', 'month', 'day', ...]
424
```
425
426
### Calendar Calculations
427
428
```typescript
429
import { week, utcweek, dayofyear, quarter } from "vega";
430
431
const dates = [
432
new Date('2023-01-01'),
433
new Date('2023-04-15'),
434
new Date('2023-07-04'),
435
new Date('2023-12-31')
436
];
437
438
dates.forEach(date => {
439
console.log({
440
date: date.toISOString(),
441
week: week(date),
442
utcWeek: utcweek(date),
443
dayOfYear: dayofyear(date),
444
quarter: quarter(date)
445
});
446
});
447
```
448
449
### Time-Based Filtering
450
451
```typescript
452
import { timeInterval, timeFloor } from "vega";
453
454
const transactions = [
455
{ date: new Date('2023-06-01T09:15:00'), amount: 100 },
456
{ date: new Date('2023-06-01T14:30:00'), amount: 250 },
457
{ date: new Date('2023-06-02T11:45:00'), amount: 75 },
458
{ date: new Date('2023-06-03T16:20:00'), amount: 200 }
459
];
460
461
// Group by day
462
const dayFloor = timeFloor('day');
463
const dailyGroups = new Map();
464
465
transactions.forEach(tx => {
466
const day = dayFloor(tx.date);
467
const dayKey = day.toISOString();
468
469
if (!dailyGroups.has(dayKey)) {
470
dailyGroups.set(dayKey, []);
471
}
472
473
dailyGroups.get(dayKey).push(tx);
474
});
475
476
// Calculate daily totals
477
const dailyTotals = Array.from(dailyGroups.entries()).map(([day, txs]) => ({
478
date: new Date(day),
479
total: txs.reduce((sum, tx) => sum + tx.amount, 0),
480
count: txs.length
481
}));
482
483
console.log(dailyTotals);
484
```
485
486
### Time Scale Configuration
487
488
```typescript
489
// Example Vega specification using time scales
490
const timeScaleSpec = {
491
"scales": [
492
{
493
"name": "xscale",
494
"type": "time",
495
"domain": {"data": "timeseries", "field": "date"},
496
"range": "width",
497
"nice": "day"
498
}
499
],
500
"axes": [
501
{
502
"orient": "bottom",
503
"scale": "xscale",
504
"format": "%b %d",
505
"tickCount": 10
506
}
507
]
508
};
509
```
510
511
### UTC vs Local Time
512
513
```typescript
514
import {
515
timeInterval,
516
utcInterval,
517
timeFloor,
518
utcFloor
519
} from "vega";
520
521
const date = new Date('2023-06-15T14:30:00Z');
522
523
// Local time operations
524
const localDay = timeInterval('day');
525
const localFloor = timeFloor('day');
526
527
// UTC time operations
528
const utcDay = utcInterval('day');
529
const utcFloorFunc = utcFloor('day');
530
531
console.log('Local day floor:', localFloor(date));
532
console.log('UTC day floor:', utcFloorFunc(date));
533
534
// Different results due to timezone differences
535
```
536
537
### Advanced Time Binning
538
539
```typescript
540
import { timeBin, timeInterval } from "vega";
541
542
const eventData = [
543
{ time: new Date('2023-06-15T08:15:30'), value: 10 },
544
{ time: new Date('2023-06-15T08:47:22'), value: 15 },
545
{ time: new Date('2023-06-15T09:12:45'), value: 8 },
546
{ time: new Date('2023-06-15T09:33:18'), value: 20 }
547
];
548
549
// Create 30-minute bins
550
const binFunc = timeBin({
551
unit: 'minutes',
552
step: 30,
553
nice: true,
554
extent: [
555
new Date('2023-06-15T08:00:00'),
556
new Date('2023-06-15T10:00:00')
557
]
558
});
559
560
// Aggregate data by time bins
561
const binnedData = new Map();
562
563
eventData.forEach(d => {
564
const binStart = binFunc(d.time);
565
const binKey = binStart.toISOString();
566
567
if (!binnedData.has(binKey)) {
568
binnedData.set(binKey, {
569
bin: binStart,
570
values: [],
571
sum: 0,
572
count: 0
573
});
574
}
575
576
const bin = binnedData.get(binKey);
577
bin.values.push(d);
578
bin.sum += d.value;
579
bin.count += 1;
580
});
581
582
const aggregated = Array.from(binnedData.values()).map(bin => ({
583
time: bin.bin,
584
average: bin.sum / bin.count,
585
total: bin.sum,
586
count: bin.count
587
}));
588
589
console.log(aggregated);
590
```