Clamp a date to a range in JavaScript
Intermediate · 4 min read
A date picker that only allows dates in the next 90 days. A "last 30 days" report that shouldn't ask for data from before the account existed. A slider that scrolls through a timeline but must stop at both ends. Each of these takes a date and keeps it inside a range. That is called clamping.
In this tutorial you will write clampDate(date, min, max). If the date is inside the range, you get it back. If it is too early, you get min. If it is too late, you get max. You need to know how to make a date with new Date(year, month, day), that months count from 0, and what getTime() returns.
Clamping a plain number
Clamping is easiest to see with numbers first. JavaScript has two helpers:
Math.max(a, b)gives the bigger of the two.Math.min(a, b)gives the smaller of the two.
Math.max(value, low) can never be below low, so it fixes values that are too small. Math.min(value, high) can never be above high, so it fixes values that are too big. Put one inside the other and you fix both ends:
const clamp = (value, low, high) => Math.min(Math.max(value, low), high);
console.log(clamp(5, 0, 10)); // 5
console.log(clamp(-3, 0, 10)); // 0
console.log(clamp(42, 0, 10)); // 10
Dates are numbers underneath
A date stores one number: its timestamp, the milliseconds since 1 January 1970. getTime() reads that number, and new Date(number) turns a number back into a date. So the plan is: clamp the timestamps, then wrap the answer in a new date.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
42 Clamp a date into a range
fairGiven a date and a minimum and maximum, return the date if it is inside the range and the nearest bound if it is not.
Stuck? Three hints, smallest first
- 1.
Math.minandMath.maxon the timestamps, then wrap the result. - 2. Nest them: clamp the low end first, then the high end.
- 3. Return a new date rather than the argument, so the caller cannot mutate your bounds by accident.
Step 1: a helper to read dates easily
Printing a whole date is noisy, so the answer uses a small iso helper that shows a date as YYYY-MM-DD:
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
console.log(iso(new Date(2026, 0, 5))); // '2026-01-05'
getMonth() + 1 turns the 0-based month into the usual 1 to 12, and padStart(2, '0') adds a leading zero to single digits.
Step 2: clamp the timestamps
Now use the same nesting as the number version, with getTime() on each date:
function clampDate(date, min, max) {
return new Date(Math.min(Math.max(date.getTime(), min.getTime()), max.getTime()));
}
const min = new Date(2026, 0, 10);
const max = new Date(2026, 0, 20);
console.log(iso(clampDate(new Date(2026, 0, 15), min, max))); // '2026-01-15'
console.log(iso(clampDate(new Date(2026, 0, 1), min, max))); // '2026-01-10'
console.log(iso(clampDate(new Date(2026, 0, 31), min, max))); // '2026-01-20'
The 15th is inside the range and comes back unchanged. The 1st is too early, so it is pulled up to the 10th. The 31st is too late, so it is pulled down to the 20th.
Step 3: the wrong turn, handing back the bound itself
A version with if checks looks simpler:
const clampSame = (date, low, high) => (date < low ? low : date > high ? high : date);
const low = new Date(2026, 0, 10);
const high = new Date(2026, 0, 20);
const picked = clampSame(new Date(2026, 0, 1), low, high);
picked.setDate(25);
console.log(iso(low)); // '2026-01-25'
It returns the right date, but it returns the same object as low. Dates can be changed in place, so when the caller moves picked to the 25th, the minimum moves too. Now every later check uses a broken range.
clampDate doesn't have this problem, because new Date(...) always makes a fresh object.
Step 4: the edges and the new object
A date exactly on a boundary is kept. The result is a different object from the bound, but it holds the same moment:
console.log(iso(clampDate(min, min, max))); // '2026-01-10'
console.log(iso(clampDate(max, min, max))); // '2026-01-20'
console.log(clampDate(min, min, max) === min); // false
console.log(clampDate(min, min, max).getTime() === min.getTime()); // true
=== on two objects asks "is this the very same object?", so it is false here. Comparing getTime() asks "is this the same moment?", which is true.
Step 5: bounds the wrong way round
What if someone passes the bounds swapped?
console.log(iso(clampDate(new Date(2026, 0, 15), max, min))); // '2026-01-10'
Math.max lifts the 15th up to the 20th, then Math.min drops it down to the 10th. The function quietly returns a bound and gives no warning. It can't tell a mistake from a deliberate call, so if the bounds come from user input, check min <= max before you clamp.
The full solution
The panel has iso and clampDate. It prints a date inside the range and one on each side. The checks cover both boundaries, the fresh object, and the swapped-bounds result. Press Run to see them.
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
// Always a fresh Date, so nothing the caller holds can be mutated through it.
function clampDate(date, min, max) {
return new Date(Math.min(Math.max(date.getTime(), min.getTime()), max.getTime()));
}
const min = new Date(2026, 0, 10);
const max = new Date(2026, 0, 20);
console.log('15/01 clamped to 10-20:', iso(clampDate(new Date(2026, 0, 15), min, max)));
console.log('01/01 clamped to 10-20:', iso(clampDate(new Date(2026, 0, 1), min, max)), '<- pulled up');
console.log('31/01 clamped to 10-20:', iso(clampDate(new Date(2026, 0, 31), min, max)), '<- pulled down');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a date inside the range is unchanged', iso(clampDate(new Date(2026, 0, 15), min, max)), '2026-01-15');
test('one below the minimum comes back as the minimum', iso(clampDate(new Date(2026, 0, 1), min, max)), '2026-01-10');
test('one above the maximum comes back as the maximum', iso(clampDate(new Date(2026, 0, 31), min, max)), '2026-01-20');
test('a date on the boundary is kept', iso(clampDate(min, min, max)), '2026-01-10');
test('and so is the other boundary', iso(clampDate(max, min, max)), '2026-01-20');
test('the result is a new object, never the argument', clampDate(min, min, max) === min, false);
test('though it holds the same instant', clampDate(min, min, max).getTime(), min.getTime());
test('bounds the wrong way round always give the maximum, so check them yourself', iso(clampDate(new Date(2026, 0, 15), max, min)), '2026-01-10');
Clamping is where a "last 30 days" control stops asking for data from before the account existed: clamp the computed start against the account's creation date and the awkward case disappears.
The last assertion is the honest caveat. If min and max arrive the wrong way round, the nested Math.min/Math.max silently returns whichever bound comes second in the nesting, with no complaint. If the bounds come from user input, check min <= max before you clamp; the function cannot tell a swapped pair from a deliberate one.
Common mistakes
- Returning
minormaxthemselves. The caller can then change your bounds by accident, as Step 3 showed. Always return a new date. - Putting the bounds in the wrong places.
Math.min(Math.max(t, max), min)always returnsmin. Remember:Math.maxgoes with the low bound,Math.minwith the high one. - Comparing results with
===. Two dates are only===when they are the same object. ComparegetTime()to check the moment.
Try it yourself
- Write
clampToNext90Days(date, today)that keeps a picked date betweentodayand 90 days later. - Make
clampDatethrow an error with a clear message whenmin > max. - Clamp the start of a "last 30 days" report so it is never earlier than an account's creation date.