Course contentsShow
← JavaScript
Lesson 1631 of 2,72335. Standard Library and Built-insFree lesson

toLocaleDateString and toLocaleTimeString

Format dates and times using locale-aware methods with options for different display styles.

toLocaleDateString and toLocaleTimeString

You'll learn how to format dates and times for different regions and languages using JavaScript's built-in locale-aware methods.

What These Methods Do

toLocaleDateString() and toLocaleTimeString() are Date methods that automatically format dates and times according to different regional conventions. Instead of getting a raw ISO string, you get human-friendly output tailored to how people in different countries expect to see dates and times.

Think of it like a smart translator that knows whether to write "12/25/2023" (US style) or "25/12/2023" (UK style) based on the locale you specify.

Basic Usage

const date = new Date(2023, 11, 25, 14, 30, 0); // Dec 25, 2023, 2:30 PM

// Date formatting
console.log(date.toLocaleDateString('en-US')); // "12/25/2023"
console.log(date.toLocaleDateString('en-GB')); // "25/12/2023"
console.log(date.toLocaleDateString('de-DE')); // "25.12.2023"

// Time formatting
console.log(date.toLocaleTimeString('en-US')); // "2:30:00 PM"
console.log(date.toLocaleTimeString('en-GB')); // "14:30:00"
console.log(date.toLocaleTimeString('de-DE')); // "14:30:00"

Using Options for Custom Styles

Both methods accept an options object to control the output format:

const date = new Date(2023, 11, 25, 14, 30, 0);

// Long date format
console.log(date.toLocaleDateString('en-US', { 
  weekday: 'long', 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric' 
})); // "Monday, December 25, 2023"

// 12-hour time without seconds
console.log(date.toLocaleTimeString('en-US', { 
  hour: 'numeric', 
  minute: 'numeric', 
  hour12: true 
})); // "2:30 PM"

Key Takeaway: Use toLocaleDateString() and toLocaleTimeString() with locale codes and options to display dates and times in region-appropriate formats automatically, making your application internationally friendly.