JavaScript Date Formats
JavaScript's Date
object can display dates in various formats. Understanding these formats ensures that date information is clear and properly localized.
Key Topics
- toString() Variants
- toLocaleDateString()
- Custom Formatting with Intl.DateTimeFormat
- JavaScript Usage in DOM
- Key Takeaways
toString() Variants
Methods like toString()
, toUTCString()
, and toDateString()
provide quick ways to display date information.
let d = new Date();
console.log(d.toString());
console.log(d.toUTCString());
console.log(d.toDateString());
Output
> "Mon Jun 21 2021 10:20:30 GMT+..."
> "Mon, 21 Jun 2021 10:20:30 GMT"
> "Mon Jun 21 2021"
Explanation: These methods present the same date in different formats (local time, UTC time, or a simpler date-only format).
toLocaleDateString()
toLocaleDateString()
formats the date according to the user's locale, producing region-specific formats.
console.log(d.toLocaleDateString("en-US"));
console.log(d.toLocaleDateString("en-GB"));
Output
> "6/21/2021" (US format)
> "21/06/2021" (GB format)
Explanation: Changing the locale string alters the date format, making it suitable for different regions.
Custom Formatting with Intl.DateTimeFormat
You can use Intl.DateTimeFormat
for more control over date and time formats.
let options = { year: "numeric", month: "long", day: "numeric" };
let formatter = new Intl.DateTimeFormat("en-US", options);
console.log(formatter.format(d));
Output
> "June 21, 2021"
Explanation: Intl.DateTimeFormat
allows specifying components and formats, producing a custom-styled date string.
JavaScript Usage in DOM
This DOM-based example shows how to display a date in a user-friendly format on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Formats in DOM</title>
</head>
<body>
<h1>Date Format Demo</h1>
<button onclick="showFormattedDate()">Show Formatted Date</button>
<p id="display"></p>
<script>
function showFormattedDate() {
let today = new Date();
let options = { weekday: "long", year: "numeric", month: "short", day: "numeric"};
let formatted = new Intl.DateTimeFormat("en-US", options).format(today);
document.getElementById("display").textContent = formatted;
}
</script>
</body>
</html>
Key Takeaways
- toString() Methods: Quickly display dates in various built-in formats.
- toLocaleDateString(): Format dates according to user locale.
- Intl.DateTimeFormat: Achieve custom formatting options.
- DOM Integration: Display well-formatted dates on webpages.