CodeBlanks Logo Icon CodeBlanks

Formatting dates

JavaScript course · Intermediate · Lesson 114/134

Learn to format dates with toLocaleString and ISO format.

Formatting dates

There are several ways to turn a date into a string. toLocaleString follows the user's locale, while toISOString gives a standard ISO string.

const d = new Date(2024, 0, 15);
d.toLocaleString(); // depends on locale
d.toISOString();    // '2024-01-15T...Z'

toLocaleString depends on the locale and may vary by machine. toISOString is always UTC and is handy when sending data to servers.

Date only and time only

When you need only the date or only the time, there are separate methods. Each returns a string.

d.toLocaleDateString(); // date only
d.toLocaleTimeString(); // time only
d.toDateString();       // 'Mon Jan 15 2024'

toLocaleDateString gives the date only and toLocaleTimeString gives the time only. toDateString offers a short English format. Pick the one that fits your need.

Exercise Get the ISO string and log it

The meeting variable holds a date. Get its ISO format with toISOString(), assign it to the iso variable, then log it with console.log.

Show example solution
MM:SS.sssZ' form.
Example solution:
const meeting = new Date('2024-06-10');
const iso = meeting.toISOString();
console.log(iso);

Test yourself

  1. Get the ISO string

    const iso = d.____;
    console.log(iso);
    Show answer
    const iso = d.toISOString();
    console.log(iso);
  2. What format does new Date('2024-01-15').toISOString() return?

    new Date('2024-01-15').toISOString()
    • 15/01/2024
    • 2024-01-15T00:00:00.000Z
    • 15 Jan 2024
    • 2024-01-15
    Show answer

    2024-01-15T00:00:00.000Z — Correct! toISOString is always UTC and uses the 'YYYY-MM-DDTHH:MM:SS.sssZ' form.

  3. Match the formatting methods

    toISOString()
    ISO format
    toLocaleString()
    locale format
    toDateString()
    date only
    toString()
    default

All lessons in Intermediate