Skip to main content
Course/Module 8/Topic 2 of 5Intermediate

JavaScript Date & Time Handling

Learn to work with dates, times, timezones, and modern date manipulation using the Date object and modern date libraries

45 minBy Priygop TeamLast updated: Feb 2026

Date & Time Basics

JavaScript provides built-in Date objects for working with dates and times. Understanding how to create, manipulate, and format dates is essential for building applications that deal with temporal data.

Creating and Manipulating Dates

Example
// Creating dates
const now = new Date();
const specificDate = new Date('2023-12-25');
const dateFromComponents = new Date(2023, 11, 25); // Month is 0-indexed
const dateFromTimestamp = new Date(1703462400000);

// Date methods
console.log(now.getFullYear()); // Current year
console.log(now.getMonth()); // Current month (0-11)
console.log(now.getDate()); // Current day
console.log(now.getDay()); // Current day of week (0-6)
console.log(now.getHours()); // Current hour
console.log(now.getMinutes()); // Current minute
console.log(now.getSeconds()); // Current second
console.log(now.getMilliseconds()); // Current millisecond

// UTC methods
console.log(now.getUTCFullYear());
console.log(now.getUTCHours());
console.log(now.getUTCDay());

// Setting date components
const date = new Date();
date.setFullYear(2024);
date.setMonth(0); // January
date.setDate(1);
date.setHours(12, 30, 0, 0); // Hour, minute, second, millisecond

// Date arithmetic
const futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7); // Add 7 days
futureDate.setMonth(futureDate.getMonth() + 1); // Add 1 month
futureDate.setFullYear(futureDate.getFullYear() + 1); // Add 1 year

// Date comparison
const date1 = new Date('2023-01-01');
const date2 = new Date('2023-12-31');

console.log(date1 < date2); // true
console.log(date1 > date2); // false
console.log(date1.getTime() === date2.getTime()); // false

// Date formatting
const date3 = new Date();
console.log(date3.toString()); // Full date string
console.log(date3.toDateString()); // Date only
console.log(date3.toTimeString()); // Time only
console.log(date3.toISOString()); // ISO format
console.log(date3.toLocaleDateString()); // Localized date
console.log(date3.toLocaleTimeString()); // Localized time

// Custom date formatting
function formatDate(date, format = 'YYYY-MM-DD') {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
}

console.log(formatDate(now, 'YYYY-MM-DD HH:mm:ss'));

// Date parsing
function parseDate(dateString) {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
        throw new Error('Invalid date string');
    }
    return date;
}

// Timezone handling
function getTimezoneOffset() {
    const date = new Date();
    const offset = date.getTimezoneOffset();
    const hours = Math.abs(Math.floor(offset / 60));
    const minutes = Math.abs(offset % 60);
    const sign = offset > 0 ? '-' : '+';
    
    return `UTC${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
}

console.log('Timezone offset:', getTimezoneOffset());

// Date utilities
function addDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}

function addMonths(date, months) {
    const result = new Date(date);
    result.setMonth(result.getMonth() + months);
    return result;
}

function addYears(date, years) {
    const result = new Date(date);
    result.setFullYear(result.getFullYear() + years);
    return result;
}

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

function getDaysInMonth(year, month) {
    return new Date(year, month + 1, 0).getDate();
}

function isWeekend(date) {
    const day = date.getDay();
    return day === 0 || day === 6;
}

function isBusinessDay(date) {
    return !isWeekend(date);
}

// Date range utilities
function getDateRange(startDate, endDate) {
    const dates = [];
    const current = new Date(startDate);
    
    while (current <= endDate) {
        dates.push(new Date(current));
        current.setDate(current.getDate() + 1);
    }
    
    return dates;
}

function getBusinessDays(startDate, endDate) {
    return getDateRange(startDate, endDate).filter(isBusinessDay);
}

// Age calculation
function calculateAge(birthDate) {
    const today = new Date();
    const birth = new Date(birthDate);
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
    }
    
    return age;
}

console.log('Age:', calculateAge('1990-05-15'));

Practice Exercise: Date Handling

Example
// Exercise: Build a Date Utility Library
class DateUtils {
    constructor() {
        this.locale = 'en-US';
        this.timezone = 'UTC';
    }
    
    setLocale(locale) {
        this.locale = locale;
        return this;
    }
    
    setTimezone(timezone) {
        this.timezone = timezone;
        return this;
    }
    
    format(date, format = 'YYYY-MM-DD') {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    }
    
    parse(dateString) {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
            throw new Error(`Invalid date: ${dateString}`);
        }
        return date;
    }
    
    add(date, amount, unit = 'days') {
        const d = new Date(date);
        
        switch (unit) {
            case 'days':
                d.setDate(d.getDate() + amount);
                break;
            case 'months':
                d.setMonth(d.getMonth() + amount);
                break;
            case 'years':
                d.setFullYear(d.getFullYear() + amount);
                break;
            case 'hours':
                d.setHours(d.getHours() + amount);
                break;
            case 'minutes':
                d.setMinutes(d.getMinutes() + amount);
                break;
            case 'seconds':
                d.setSeconds(d.getSeconds() + amount);
                break;
        }
        
        return d;
    }
    
    subtract(date, amount, unit = 'days') {
        return this.add(date, -amount, unit);
    }
    
    diff(date1, date2, unit = 'days') {
        const d1 = new Date(date1);
        const d2 = new Date(date2);
        const diffMs = d2.getTime() - d1.getTime();
        
        switch (unit) {
            case 'days':
                return Math.floor(diffMs / (1000 * 60 * 60 * 24));
            case 'hours':
                return Math.floor(diffMs / (1000 * 60 * 60));
            case 'minutes':
                return Math.floor(diffMs / (1000 * 60));
            case 'seconds':
                return Math.floor(diffMs / 1000);
            case 'milliseconds':
                return diffMs;
        }
    }
    
    isBetween(date, start, end) {
        const d = new Date(date);
        const s = new Date(start);
        const e = new Date(end);
        return d >= s && d <= e;
    }
    
    isWeekend(date) {
        const d = new Date(date);
        const day = d.getDay();
        return day === 0 || day === 6;
    }
    
    isBusinessDay(date) {
        return !this.isWeekend(date);
    }
    
    getBusinessDays(start, end) {
        const dates = [];
        const current = new Date(start);
        const endDate = new Date(end);
        
        while (current <= endDate) {
            if (this.isBusinessDay(current)) {
                dates.push(new Date(current));
            }
            current.setDate(current.getDate() + 1);
        }
        
        return dates;
    }
    
    getWeekNumber(date) {
        const d = new Date(date);
        d.setHours(0, 0, 0, 0);
        d.setDate(d.getDate() + 4 - (d.getDay() || 7));
        const yearStart = new Date(d.getFullYear(), 0, 1);
        return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    }
    
    getQuarter(date) {
        const month = new Date(date).getMonth();
        return Math.floor(month / 3) + 1;
    }
    
    getFiscalYear(date, startMonth = 0) {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = d.getMonth();
        
        if (month < startMonth) {
            return year - 1;
        }
        return year;
    }
}

// Exercise: Build a Calendar Generator
class CalendarGenerator {
    constructor(year, month) {
        this.year = year;
        this.month = month;
        this.dateUtils = new DateUtils();
    }
    
    generate() {
        const firstDay = new Date(this.year, this.month, 1);
        const lastDay = new Date(this.year, this.month + 1, 0);
        const startDate = new Date(firstDay);
        startDate.setDate(startDate.getDate() - firstDay.getDay());
        
        const calendar = [];
        const current = new Date(startDate);
        
        for (let week = 0; week < 6; week++) {
            const weekDays = [];
            for (let day = 0; day < 7; day++) {
                weekDays.push({
                    date: new Date(current),
                    isCurrentMonth: current.getMonth() === this.month,
                    isToday: this.dateUtils.format(current) === this.dateUtils.format(new Date()),
                    isWeekend: this.dateUtils.isWeekend(current)
                });
                current.setDate(current.getDate() + 1);
            }
            calendar.push(weekDays);
        }
        
        return calendar;
    }
    
    getMonthName() {
        return new Date(this.year, this.month).toLocaleDateString(this.dateUtils.locale, { month: 'long' });
    }
    
    getYearName() {
        return this.year.toString();
    }
    
    nextMonth() {
        if (this.month === 11) {
            this.year++;
            this.month = 0;
        } else {
            this.month++;
        }
    }
    
    previousMonth() {
        if (this.month === 0) {
            this.year--;
            this.month = 11;
        } else {
            this.month--;
        }
    }
}

// Test the exercises
const dateUtils = new DateUtils();

const today = new Date();
const future = dateUtils.add(today, 7, 'days');
const past = dateUtils.subtract(today, 30, 'days');

console.log('Today:', dateUtils.format(today));
console.log('Future:', dateUtils.format(future));
console.log('Past:', dateUtils.format(past));
console.log('Days between:', dateUtils.diff(past, future, 'days'));
console.log('Is weekend:', dateUtils.isWeekend(today));

const calendar = new CalendarGenerator(2024, 0); // January 2024
const monthCalendar = calendar.generate();

console.log(`Calendar for ${calendar.getMonthName()} ${calendar.getYearName()}:`);
monthCalendar.forEach(week => {
    week.forEach(day => {
        const marker = day.isToday ? '*' : day.isCurrentMonth ? ' ' : '.';
        process.stdout.write(`${day.date.getDate().toString().padStart(2)}${marker} `);
    });
    console.log();
});
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep