JS Tutorial



JS DATES


JavaScript Dates 📅

JavaScript provides a built-in Date object for handling dates and times. You can create, format, and manipulate date and time values with various methods.

📌 Creating a Date

You can create date objects in several ways:

let now = new Date();                           // current date & time
let specific = new Date("2025-05-08");          // specific date
let components = new Date(2025, 4, 8, 14, 30);   // year, month (0-11), day, hour, minute
  

⏱ Getting Date Components

You can extract parts of the date using these methods:

  • getFullYear() → Year
  • getMonth() → Month (0-11)
  • getDate() → Day of the month
  • getDay() → Day of the week (0 = Sunday)
  • getHours(), getMinutes(), getSeconds()
let date = new Date();
date.getFullYear();   // 2025
date.getMonth();      // 4 (May)
date.getDate();       // 8
  

🛠️ Setting Date Components

let d = new Date();
d.setFullYear(2030);
d.setMonth(0);       // January
d.setDate(1);
  

⏳ Date Methods for Formatting

  • toDateString() – Human-readable date
  • toTimeString() – Human-readable time
  • toLocaleDateString() – Localized date
  • toISOString() – ISO format
let d = new Date();
d.toDateString();        // "Thu May 08 2025"
d.toTimeString();        // "14:45:30 GMT+0530 (India Standard Time)"
d.toLocaleDateString();  // "8/5/2025"
d.toISOString();         // "2025-05-08T09:15:00.000Z"
  

⏱ Live Example: Show Current Time

🔁 Bonus: Countdown Example

let future = new Date("2025-12-31");
let today = new Date();
let diff = future - today;
let daysLeft = Math.floor(diff / (1000 * 60 * 60 * 24));
console.log("Days until New Year:", daysLeft);
  
Try It Yourself: Use new Date("YYYY-MM-DD") format and subtract to get time differences.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review