What Are JavaScript Dates And Times? See Examples

JavaScript provides the Date object to work with dates and times. You can get the current date, manipulate dates, and perform calculations such as finding the difference between two dates.

This blog explains how to use the Date object with practical examples.


1. Creating a Date Object

Current Date and Time

let now = new Date();
console.log(now);

Specific Date

let birthday = new Date("2000-12-02");
console.log(birthday);

Using Year, Month, Day

let specificDate = new Date(2025, 11, 2); // Month is 0-based (11 = December)
console.log(specificDate);

2. Getting Date and Time Components

let now = new Date();
console.log(now.getFullYear()); // 2025
console.log(now.getMonth());    // 11 (December)
console.log(now.getDate());     // 2
console.log(now.getDay());      // 2 (Tuesday, 0 = Sunday)
console.log(now.getHours());    // 19
console.log(now.getMinutes());  // 45
console.log(now.getSeconds());  // 30

3. Setting Date and Time Components

let date = new Date();
date.setFullYear(2026);
date.setMonth(0);   // January
date.setDate(15);
date.setHours(10);
date.setMinutes(30);
console.log(date);

4. Date Methods

Convert Date to String

let now = new Date();
console.log(now.toDateString());  // Tue Dec 02 2025
console.log(now.toTimeString());  // 19:45:30 GMT+0530
console.log(now.toISOString());   // 2025-12-02T14:15:30.000Z

Get Time in Milliseconds

console.log(now.getTime()); // milliseconds since Jan 1, 1970

5. Date Calculations

You can calculate the difference between two dates:

let start = new Date("2025-12-01");
let end = new Date("2025-12-31");

let diff = end - start; // difference in milliseconds
let days = diff / (1000 * 60 * 60 * 24); // convert to days
console.log(days); // 30

6. Why Dates Are Important

  • Display current date and time
  • Schedule tasks or events
  • Track time intervals
  • Perform date calculations in applications

Conclusion

The JavaScript Date object allows you to create, manipulate, and format dates and times efficiently. Understanding Date methods is crucial for building dynamic web applications that rely on time or date calculations.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *