CodeBlanks Logo Icon CodeBlanks

Summary - Date and time

JavaScript course · Intermediate · Lesson 117/134

Build a birthday countdown app using Date and Intl.DateTimeFormat.

Summary - Date and time

In this group you learned the Date object: creating, reading parts, formatting, Intl.DateTimeFormat and date arithmetic. Now you will combine them in a birthday countdown.

const today = new Date();
const birthday = new Date(2024, 7, 3);
const diff = birthday.getTime() - today.getTime();
const days = Math.floor(diff / MS_PER_DAY);

First create the date, then format it, and finally compute the difference. Two mini tasks will reinforce every step.

Exercise Format the birthday

Assign this year's birthday to birthday (for example new Date(2024, 7, 3)). Format it with Intl.DateTimeFormat('en-US', { weekday: 'long', day: 'numeric', month: 'long' }) and log the result with console.log.

Show example solution
Create the birthday with new Date, then format it with Intl.DateTimeFormat.
Example solution:
const birthday = new Date(2024, 7, 3);
const fmt = new Intl.DateTimeFormat('en-US', { weekday: 'long', day: 'numeric', month: 'long' });
console.log(fmt.format(birthday));

Exercise Compute the days left

Compute the day difference between the today and birthday dates. Use the MS_PER_DAY = 24 * 60 * 60 * 1000 constant, get the difference with getTime, convert it to days with Math.floor and log it with console.log.

Show example solution
Take the difference of today and birthday timestamps, divide by MS_PER_DAY and round down with Math.floor.
Example solution:
const today = new Date('2024-01-10');
const birthday = new Date('2024-02-10');
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const diffMs = birthday.getTime() - today.getTime();
const daysLeft = Math.floor(diffMs / MS_PER_DAY);
console.log(daysLeft);

Test yourself

  1. Which two values are needed to compute the days left in a birthday countdown?

    • Hour and minute
    • Year and month
    • Today's date and the birthday date
    • Weekday and time zone
    Show answer

    Today's date and the birthday date — Correct! The difference between today and the birthday timestamps gives the days left.

  2. Match the summary parts

    new Date()
    create a date
    getFullYear()
    read the year
    toISOString()
    convert to ISO
    Intl.DateTimeFormat
    locale format

All lessons in Intermediate