JavaScript - Date & Math
Overview
Estimated time: 35–45 minutes
Learn how to create and format dates, perform date arithmetic, handle time zones, and use common Math utilities for rounding and random numbers.
Learning Objectives
- Create
Date
objects safely and format them. - Compute differences, add/subtract days, and handle UTC vs local time.
- Use
Math
for rounding, clamping, and random ranges.
Prerequisites
- JavaScript - Numbers & BigInt
- JavaScript - RegExp (recommended)
Creating dates
// Now
const now = new Date(); // local time
// From timestamp (ms since Unix epoch)
const t = Date.now(); // number
const fromTs = new Date(t); // Date
// From ISO 8601 string (portable)
const iso = new Date('2025-09-05T12:00:00Z'); // UTC
// Components: months are 0-based (0=Jan, 11=Dec)
const local = new Date(2025, 8, 5, 9, 30); // 2025-09-05 09:30 local
// UTC factory to avoid DST surprises when building calendar dates
const utc = new Date(Date.UTC(2025, 8, 5, 9, 30));
Formatting and parts
now.toISOString(); // '2025-09-05T14:22:31.123Z'
now.getFullYear(); // local year
now.getUTCFullYear(); // UTC year
now.getTimezoneOffset(); // minutes difference from UTC
Date arithmetic
// Difference in days
const a = new Date('2025-09-01T00:00:00Z');
const b = new Date('2025-09-05T00:00:00Z');
const diffMs = b - a; // number (ms)
const diffDays = diffMs / (1000*60*60*24); // 4
// Add days (UTC-safe approach)
function addDaysUTC(d, days) {
const nd = new Date(d.getTime());
nd.setUTCDate(nd.getUTCDate() + days);
return nd;
}
addDaysUTC(new Date('2025-09-05T00:00:00Z'), 7).toISOString();
// '2025-09-12T00:00:00.000Z'
Math utilities
// Rounding
Math.floor(3.7); // 3
Math.ceil(3.1); // 4
Math.round(3.5); // 4
Math.trunc(-3.9); // -3
// Clamp
const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
clamp(15, 0, 10); // 10
// Random in range [min, max) for numbers
function randRange(min, max) {
return Math.random() * (max - min) + min;
}
// Random integer in [min, max] inclusive
function randInt(min, max) {
min = Math.ceil(min); max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Common Pitfalls
- Months are 0-based: September is 8, not 9.
- DST shifts: Adding hours across DST boundaries can skip/repeat times; prefer UTC arithmetic for calendar math.
- Parsing: Non-ISO date strings are locale-dependent. Prefer ISO 8601 or numeric constructors.
- Time zones:
Date
stores a UTC timestamp; formatting decides local vs UTC. - Random:
Math.random()
is not cryptographically secure; usecrypto.getRandomValues
when needed.
Try it
Run this snippet to see date arithmetic and random utilities: