How to use the Date object in JavaScript

1 Answer

0 votes
"use strict";

/*
 * Date Utility Functions
 * ----------------------
 * This file demonstrates:
 * 1. Creating Date objects
 * 2. Retrieving date components
 * 3. Formatting dates
 * 4. Performing date calculations
 * 5. Using a custom helper function
 */


/*
 * Key Date Methods
 * ----------------
 * const date = new Date();
 *
 * date.getFullYear();   // Year
 * date.getMonth();      // Month (0-11)
 * date.getDate();       // Day of month
 * date.getDay();        // Day of week (0-6)
 *
 * date.getHours();
 * date.getMinutes();
 * date.getSeconds();
 * 
 * date.setDate(15);
 * date.setMonth(11);
 *
 * date.toISOString();
 * date.toLocaleDateString();
 * date.toLocaleString();
 */

/**
 * Formats a Date object as YYYY-MM-DD HH:mm:ss
 *
 * @param {Date} date - The Date object to format.
 * @returns {string} Formatted date string.
 */
function formatDate(date) {
    if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
        throw new Error("Invalid Date object.");
    }

    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 `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * Adds a specified number of days to a date.
 *
 * @param {Date} date - Original date.
 * @param {number} days - Number of days to add.
 * @returns {Date} New Date object.
 */
function addDays(date, days) {
    if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
        throw new Error("Invalid Date object.");
    }

    const result = new Date(date);
    result.setDate(result.getDate() + days);
  
    return result;
}

// ----------------------------------------------------
// Usage Examples
// ----------------------------------------------------

// 1. Current date and time
const now = new Date();
console.log("Current Date Object:");
console.log(now);

// 2. Formatted current date
console.log("\nFormatted Current Date:");
console.log(formatDate(now));

// 3. Specific date
const birthday = new Date("1995-07-15T10:30:00");

console.log("\nSpecific Date:");
console.log(formatDate(birthday));

// 4. Accessing date parts
console.log("\nDate Components:");
console.log("Year:", birthday.getFullYear());
console.log("Month:", birthday.getMonth() + 1); // Months are 0-based
console.log("Day:", birthday.getDate());
console.log("Hour:", birthday.getHours());
console.log("Minute:", birthday.getMinutes());

// 5. Adding days
const futureDate = addDays(now, 30);

console.log("\n30 Days From Now:");
console.log(formatDate(futureDate));

// 6. Date difference in days
const diffMs = futureDate - now;
const diffDays = diffMs / (1000 * 60 * 60 * 24);

console.log("\nDifference:");
console.log(`${diffDays} days`);

// 7. ISO format (recommended for APIs)
console.log("\nISO Format:");
console.log(now.toISOString());

// 8. Locale-based formatting
console.log("\nLocalized Format:");
console.log(
    now.toLocaleString("en-US", {
        dateStyle: "full",
        timeStyle: "long"
    })
);


/*
run:

Current Date Object:
2026-10-16T15:10:51.402Z

Formatted Current Date:
2026-10-16 15:10:51

Specific Date:
1995-07-15 10:30:00

Date Components:
Year: 1995
Month: 7
Day: 15
Hour: 10
Minute: 30

30 Days From Now:
2026-11-15 15:10:51

Difference:
30 days

ISO Format:
2026-10-16T15:10:51.402Z

Localized Format:
Friday, October 16, 2026 at 3:10:51 PM UTC

*/

 



answered Oct 16 by avibootz

Related questions

1 answer 221 views
1 answer 248 views
1 answer 228 views
...