JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Date Objects

8 April 2025 | Category:

JavaScript provides a built-in Date object to work with dates and times.

You can create a date, get parts of a date (like day, month, year), set new values, and even format or compare dates.


âś… 1. Creating a Date Object

đź“… Current Date and Time:

const now = new Date();
console.log(now); // Shows current date and time

đź›  Create Date with Specific Values:

const birthday = new Date(2025, 3, 8); // Months start from 0 (0 = Jan)
console.log(birthday); // Tue Apr 08 2025
const customDate = new Date("2024-12-25T10:00:00");
console.log(customDate); // Wed Dec 25 2024 10:00:00

âś… 2. Date Get Methods

These methods extract specific parts from a Date object:

const today = new Date();

today.getFullYear(); // 2025
today.getMonth();    // 3 (April, since Jan = 0)
today.getDate();     // 8
today.getDay();      // 2 (0 = Sunday, 1 = Monday, etc.)
today.getHours();    // 13 (in 24-hour format)
today.getMinutes();  // 45
today.getSeconds();  // 30
today.getMilliseconds(); // 123

âś… 3. Date Set Methods

You can also change parts of a date:

const future = new Date();

future.setFullYear(2030);
future.setMonth(11);       // December
future.setDate(25);        // 25th

console.log(future); // Wed Dec 25 2030

âś… 4. Formatting Dates

🔹 Convert to String:

const date = new Date();

date.toString();     // Full date and time string
date.toDateString(); // Only the date
date.toTimeString(); // Only the time
date.toISOString();  // ISO 8601 format (useful for APIs)

âś… 5. Comparing Dates

You can compare dates using relational operators:

const d1 = new Date("2025-01-01");
const d2 = new Date("2024-01-01");

console.log(d1 > d2);  // true

Or get the time difference in milliseconds:

const diff = d1 - d2;
console.log(diff); // Milliseconds difference

âś… 6. Get Timestamp (Milliseconds since Jan 1, 1970)

const now = new Date();
console.log(now.getTime()); // e.g., 1744062200000

You can also use:

Date.now(); // Current timestamp

📌 Summary Table

MethodDescription
new Date()Creates a new Date object
getFullYear()Gets the year
getMonth()Gets the month (0–11)
getDate()Gets the day of the month (1–31)
getDay()Gets the weekday (0–6)
setFullYear(y)Sets the year
toISOString()Converts date to ISO string
getTime()Gets timestamp in milliseconds

đź§  Final Thoughts

  • Use Date for working with times, timestamps, and scheduling.
  • Remember: Months are 0-indexed (0 = January, 11 = December).
  • Date objects are powerful and essential for any time-based logic.