Index

Working with Dates and Times

JavaScript for Beginners

13.1 Creating and Formatting Dates

Working with dates and times is a common task in JavaScript, and the Date object provides a powerful way to handle this.

Creating Date Objects

You can create a Date object in several ways:

const now = new Date();
console.log(now); // Outputs current date and time, e.g. 2025-06-23T14:30:00.000Z
const specificDate = new Date('2025-12-25T10:00:00');
console.log(specificDate); // Dec 25, 2025, 10:00 AM
const customDate = new Date(2025, 11, 25, 10, 0, 0); 
// Note: Month is zero-based, so 11 = December
console.log(customDate);

Formatting Dates

JavaScript provides several built-in methods to convert Date objects into readable strings:

console.log(now.toLocaleDateString()); // e.g. "6/23/2025" in US locale
console.log(now.toLocaleDateString('en-GB')); // "23/06/2025" for UK
console.log(now.toISOString()); // "2025-06-23T14:30:00.000Z"

Custom Formatting with Getters

You can also extract specific parts of the date and build your own format:

Example:

const year = now.getFullYear();
const month = now.getMonth() + 1; // Add 1 because months start at 0
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();

const formatted = `${day}/${month}/${year} ${hours}:${minutes}`;
console.log(formatted); // e.g. "23/6/2025 14:30"

Practical Example: Formatting the Current Date

const currentDate = new Date();

console.log('Locale date:', currentDate.toLocaleDateString());
console.log('ISO string:', currentDate.toISOString());
console.log('Custom format:', `${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getFullYear()}`);

This outputs the current date in multiple human- and machine-friendly formats, helping you display or process dates in the way your application needs.

Mastering date creation and formatting unlocks powerful capabilities for handling time-based data in JavaScript!

Index

13.2 Timestamps and Time Differences

When working with dates and times in JavaScript, understanding timestamps and how to calculate differences between dates is crucial for many applications — such as measuring elapsed time, creating countdowns, or even calculating someone's age.

What is a Timestamp?

A timestamp is a way of representing a specific moment in time as a single number. In JavaScript, timestamps are expressed as the number of milliseconds that have passed since the Unix epoch, which is January 1, 1970, 00:00:00 UTC. This format allows for precise time calculations and comparisons.

Getting the Current Timestamp

You can get the current timestamp using:

// Using Date.now()
const nowTimestamp = Date.now();
console.log(nowTimestamp);  // e.g., 1687551937264

// Using getTime() on a Date object
const now = new Date();
const timestampFromDate = now.getTime();
console.log(timestampFromDate);  // Should be the same as Date.now()

Calculating Time Differences

To find the difference between two dates, you subtract their timestamps. The result is the difference in milliseconds, which you can then convert to seconds, minutes, hours, or days.

Example: Calculate Days Between Two Dates

const date1 = new Date('2025-07-01');
const date2 = new Date('2025-07-10');

const diffInMs = date2.getTime() - date1.getTime();  // Difference in milliseconds
const millisecondsPerDay = 1000 * 60 * 60 * 24;     // 86,400,000 ms in a day
const diffInDays = diffInMs / millisecondsPerDay;

console.log(`Days between: ${diffInDays}`);  // Outputs: Days between: 9

Real-World Examples

Measuring Elapsed Time

Suppose you want to measure how long a task takes in your program:

const startTime = Date.now();

// Simulate some process with a delay
setTimeout(() => {
  const endTime = Date.now();
  const elapsedTimeMs = endTime - startTime;
  console.log(`Elapsed time: ${elapsedTimeMs} milliseconds`);
}, 2000);

This code measures the time elapsed during a 2-second delay.

Countdown Timer

You can calculate the remaining time until a future event by subtracting the current timestamp from the event’s timestamp.

const futureDate = new Date('2025-12-31T23:59:59');
const now = Date.now();

const timeLeftMs = futureDate.getTime() - now;

if (timeLeftMs > 0) {
  const secondsLeft = Math.floor(timeLeftMs / 1000);
  console.log(`Countdown: ${secondsLeft} seconds left`);
} else {
  console.log("The event has already occurred!");
}

Calculating Age from a Birthdate

You can calculate someone's age by comparing their birthdate to the current date:

function calculateAge(birthDateStr) {
  const birthDate = new Date(birthDateStr);
  const now = new Date();

  const diffInMs = now.getTime() - birthDate.getTime();
  const millisecondsPerYear = 1000 * 60 * 60 * 24 * 365.25; // Approximate, accounts for leap years

  return Math.floor(diffInMs / millisecondsPerYear);
}

const age = calculateAge('1990-06-23');
console.log(`Age: ${age} years`);

Summary

Mastering timestamps and date differences opens up many possibilities for handling time in JavaScript!

Index

13.3 Timers: setTimeout, setInterval

JavaScript provides two essential timer functions — setTimeout and setInterval — that allow you to schedule code execution after a delay or repeatedly at intervals. These are incredibly useful for creating dynamic behaviors like delayed messages, animations, countdowns, and polling.

setTimeout: Delayed Execution

setTimeout schedules a function to run once after a specified number of milliseconds.

Basic Syntax

const timeoutId = setTimeout(functionToRun, delayInMilliseconds);

Example: Show a Message After 3 Seconds

setTimeout(() => {
  console.log("This message appears after 3 seconds.");
}, 3000);

After 3 seconds, the message will appear in the console.

Canceling a Timeout

If you need to cancel a scheduled timeout before it runs, save its ID and call clearTimeout():

const timeoutId = setTimeout(() => {
  console.log("You won't see this message.");
}, 5000);

// Cancel the timeout before it runs
clearTimeout(timeoutId);

setInterval: Repeated Execution

setInterval runs a function repeatedly at fixed intervals (in milliseconds) until stopped.

Basic Syntax

const intervalId = setInterval(functionToRun, intervalInMilliseconds);

Example: Counter Increment Every Second

let count = 0;

const intervalId = setInterval(() => {
  count++;
  console.log(`Count: ${count}`);
  
  if (count >= 5) {
    clearInterval(intervalId);  // Stop after 5 counts
    console.log("Counter stopped.");
  }
}, 1000);

This code increments and logs the counter every second. After reaching 5, it stops the interval.

Canceling an Interval

Use clearInterval() with the interval ID to stop repeated execution:

clearInterval(intervalId);

Best Practices & Common Pitfalls

Practical Example: Delayed Greeting and Repeated Reminder

// Show a greeting after 2 seconds
const greetingTimeout = setTimeout(() => {
  console.log("Hello! Welcome to our site.");
}, 2000);

// Every 3 seconds, remind the user to check notifications
let reminderCount = 0;
const reminderInterval = setInterval(() => {
  reminderCount++;
  console.log("Don't forget to check your notifications!");
  
  if (reminderCount === 3) {
    clearInterval(reminderInterval);
    console.log("Reminder stopped after 3 times.");
  }
}, 3000);

Summary

Function Purpose Cancel with
setTimeout Run code once after a delay clearTimeout()
setInterval Run code repeatedly at intervals clearInterval()

Timers are simple yet powerful tools to control timing in your JavaScript programs. Use them wisely to create smooth user experiences, animations, and automated tasks!

Index