JavaScript Dates: A Comprehensive Guide for Developers

Java Script @ Freshers.in

JavaScript Date objects are essential for handling dates and times in web applications. They allow developers to create, manipulate, and display dates and times, providing a range of functionalities vital for dynamic web content.

Creating Date Objects

To work with dates, you first need to create a Date object. There are several ways to do this:

Default Date: Create a new Date object with the current date and time:

let currentDate = new Date();

Date String: Use a date string to create a specific date:

let specificDate = new Date("2023-12-01");

Date Components: Specify year, month, and day to create a date:

let customDate = new Date(2023, 11, 1); // Note: January is 0!

Displaying Dates

JavaScript provides methods to get readable date and time formats. For instance:

let date = new Date();
console.log(date.toDateString()); // Displays date in a readable format

Date Manipulation

JavaScript Date objects offer methods to set and get date components such as year, month, day, hour, minute, and second. For example:

let date = new Date();
date.setFullYear(2024);
console.log(date.getFullYear()); // Outputs: 2024

Practical Examples

Calculating Age:

function calculateAge(dob) {
    let birthDate = new Date(dob);
    let difference = Date.now() - birthDate.getTime();
    let ageDate = new Date(difference); 
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}
console.log(calculateAge("2000-01-01")); // Replace with actual date of birth

Formatting Date:

function formatDate(date) {
    let d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();
    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;
    return [year, month, day].join('-');
}
console.log(formatDate(new Date())); // Outputs today's date in YYYY-MM-DD format

Get more articles on Java Script

Author: user