Module 17 : Understanding Date and Time in JavaScript is essential for many applications such as booking systems, time tracking apps, countdowns, calendars, and more. JavaScript offers a built-in object called Date to work with dates and times.
📘 JavaScript Date Object – Overview
JavaScript's Date object represents a single moment in time in a platform-independent format. It contains both date and time down to the millisecond.
✅ Creating a Date Object
There are several ways to create a new date:
javascript
code
// Current date and time let now = new Date(); // Specific date and time (year, monthIndex, day, hour, minute, second, millisecond) let specific = new Date(2025, 5, 14, 10, 30, 0); // June 14, 2025, 10:30:00 // From a date-time string let fromString = new Date("2025-06-14T10:30:00"); // From milliseconds since Unix Epoch let fromEpoch = new Date(1623672000000);
⚠️ Note: In JavaScript, months are zero-indexed (0 = January, 11 = December)
🔍 Date Methods – Accessing and Modifying
Here are the most commonly used methods:
📅 Getters
javascript
code
let date = new Date(); date.getFullYear(); // e.g. 2025 date.getMonth(); // 0–11 date.getDate(); // 1–31 date.getDay(); // 0 (Sunday) – 6 (Saturday) date.getHours(); // 0–23 date.getMinutes(); // 0–59 date.getSeconds(); // 0–59 date.getMilliseconds(); // 0–999
🛠️ Setters
javascript
code
date.setFullYear(2026); date.setMonth(11); // December date.setDate(25); date.setHours(12); date.setMinutes(0);
Exercises with Explanation
🔁 Example 1: Display Current Time Every Second (Clock)
javascript
code
function startClock() { setInterval(() => { const now = new Date(); console.log( `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}` ); }, 1000); } startClock();
Explanation:
setInterval repeatedly runs the function every 1000ms.
Date fetches current time on each iteration.
Logs hours:minutes:seconds to simulate a clock.
📅 Example 2: Calculate Days Between Two Dates
javascript
code
function daysBetween(date1, date2) { const msPerDay = 1000 * 60 * 60 * 24; const diffInMs = Math.abs(date2 - date1); return Math.floor(diffInMs / msPerDay); } // Example let d1 = new Date('2025-06-01'); let d2 = new Date('2025-06-14'); console.log(daysBetween(d1, d2)); // Outputs: 13
Explanation:
Convert time difference to days.
Math.abs() ensures we get a positive value regardless of order.
⏳ Example 3: Countdown Timer
javascript
code
function countdown(toDate) { let timer = setInterval(() => { let now = new Date(); let distance = toDate - now; if (distance <= 0) { clearInterval(timer); console.log("Countdown complete!"); return; } let days = Math.floor(distance / (1000 * 60 * 60 * 24)); let hours = Math.floor((distance / (1000 * 60 * 60)) % 24); let minutes = Math.floor((distance / (1000 * 60)) % 60); let seconds = Math.floor((distance / 1000) % 60); console.log(`${days}d ${hours}h ${minutes}m ${seconds}s`); }, 1000); } // Example: Countdown to July 1, 2025 countdown(new Date("2025-07-01T00:00:00"));
Exercise Module
🧑💻 Instructions
Understand how to create, manipulate, and display dates and times in JavaScript.
Create a date object for your birthdate.
Display the day of the week you were born.
Write a function that adds 100 days to a given date.
Write a function that tells if a date is in the past or future.
Display a clock on a web page.
Example Code:
javascript
code
function getBirthDayOfWeek(dateString) { const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let date = new Date(dateString); return days[date.getDay()]; } console.log(getBirthDayOfWeek("2000-01-01")); // Example output: Saturday
📚 Research: How JavaScript Handles Time
Timezones and UTC
JavaScript Date objects are created in local time but can also be managed in UTC.
javascript
code
let date = new Date(); console.log(date.toUTCString()); console.log(date.toLocaleString());
Parsing Strings
Date parsing supports ISO 8601 format (YYYY-MM-DDTHH:mm:ss) reliably across browsers.
Epoch Time
JavaScript internally stores dates as milliseconds since January 1, 1970 UTC (Unix Epoch).
javascript
code
let now = new Date(); console.log(now.getTime()); // Milliseconds since Epoch
Limitations
Limited timezone support (use libraries like Luxon, date-fns, or Moment.js for complex cases).
No built-in formatting customization beyond toLocaleString.
🔧 Libraries to Enhance Date Handling
Luxon – Modern and powerful.
date-fns – Functional and modular.
Moment.js – Older but widely used (now in maintenance mode).
bash
code
npm install luxon
Example with Luxon:
javascript
code
const { DateTime } = require("luxon"); let dt = DateTime.local().plus({ days: 100 }); console.log(dt.toLocaleString(DateTime.DATETIME_MED));
🧠 Summary
Topic
Key Point
Date object
Built-in JavaScript object to handle time/date
Get/Set Methods
Use .getFullYear(), .setDate() etc.
Use Cases
Clocks, timers, scheduling, formatting, comparisons
Libraries
Use Luxon or date-fns for better handling and formatting
Best Practice
Always normalize timezone, prefer ISO 8601 formats
No comments:
Post a Comment