Date Arithmetic

Add and subtract time from dates

BeginnerTopic: Date/Time Programs
Back

JavaScript Date Arithmetic Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Add/subtract days
function addDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}

function subtractDays(date, days) {
    return addDays(date, -days);
}

const today = new Date();
console.log('Today:', today);
console.log('Tomorrow:', addDays(today, 1));
console.log('Yesterday:', subtractDays(today, 1));

// Method 2: Add/subtract months
function addMonths(date, months) {
    const result = new Date(date);
    result.setMonth(result.getMonth() + months);
    return result;
}

console.log('Next month:', addMonths(today, 1));
console.log('Last month:', addMonths(today, -1));

// Method 3: Add/subtract years
function addYears(date, years) {
    const result = new Date(date);
    result.setFullYear(result.getFullYear() + years);
    return result;
}

console.log('Next year:', addYears(today, 1));

// Method 4: Add/subtract hours
function addHours(date, hours) {
    const result = new Date(date);
    result.setHours(result.getHours() + hours);
    return result;
}

console.log('In 2 hours:', addHours(today, 2));

// Method 5: Add/subtract minutes
function addMinutes(date, minutes) {
    const result = new Date(date);
    result.setMinutes(result.getMinutes() + minutes);
    return result;
}

console.log('In 30 minutes:', addMinutes(today, 30));

// Method 6: Using timestamps
function addTime(date, milliseconds) {
    return new Date(date.getTime() + milliseconds);
}

console.log('Add 1 day (ms):', addTime(today, 24 * 60 * 60 * 1000));
console.log('Add 1 hour (ms):', addTime(today, 60 * 60 * 1000));

// Method 7: Date difference
function dateDifference(date1, date2) {
    const diff = Math.abs(date1 - date2);
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    return { days, hours, minutes };
}

const date1 = new Date('2024-01-01');
const date2 = new Date('2024-01-15');
console.log('Difference:', dateDifference(date1, date2));
Output
Today: 2024-01-15T10:30:45.123Z
Tomorrow: 2024-01-16T10:30:45.123Z
Yesterday: 2024-01-14T10:30:45.123Z
Next month: 2024-02-15T10:30:45.123Z
Last month: 2023-12-15T10:30:45.123Z
Next year: 2025-01-15T10:30:45.123Z
In 2 hours: 2024-01-15T12:30:45.123Z
In 30 minutes: 2024-01-15T11:00:45.123Z
Add 1 day (ms): 2024-01-16T10:30:45.123Z
Add 1 hour (ms): 2024-01-15T11:30:45.123Z
Difference: { days: 14, hours: 0, minutes: 0 }

Understanding Date Arithmetic

Date arithmetic manipulates dates.

Methods

setDate/setMonth/setFullYear
setHours/setMinutes/setSeconds
Using timestamps

Adding Time

Days: setDate(getDate() + n)
Months: setMonth(getMonth() + n)
Years: setFullYear(getFullYear() + n)
Hours/Minutes: setHours/getMinutes

Subtracting

Use negative values
Or subtract from timestamp

Date Difference

Calculate milliseconds
Convert to days/hours/minutes
Handle timezones

Best Practices

Create new Date objects
Don't mutate original
Handle month/year boundaries
Use timestamps for precision

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Date Arithmetic

This JavaScript program is part of the "Date/Time Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents