Formatting Dates
Formatting dates in JavaScript can be done manually, or by using libraries like moment.js
. However, with modern JavaScript, you can also achieve formatting using Intl.DateTimeFormat
:
Example: The code initializes a `Date` object representing the current date. It then formats this date using the `Intl.DateTimeFormat` constructor with the locale set to ‘en-US’, displaying it in the format ‘month/day/year’.
let date = new Date();
let formattedDate = new Intl.DateTimeFormat('en-US').format(date);
console.log(formattedDate); // Output: "2/23/2024" (assuming today's date is Feb 23, 2024)
Output
2/23/2024
JavaScript Date
The JavaScript Date
object serves as a fundamental component for managing date and time values within applications. It encapsulates a moment in time, allowing developers to perform various operations such as date arithmetic, formatting, and manipulation.
The time value represented by a Date
object is measured in milliseconds since the Unix Epoch, which is defined as January 1, 1970, at 00:00:00 UTC (Coordinated Universal Time). This epoch serves as a reference point for calculating time intervals and representing dates across different time zones.
Creating a Date
object involves invoking the new Date()
constructor, which initializes the object with the current date and time based on the system’s local time zone. Additionally, the Date
constructor supports various parameter options to specify a specific date and time, including year, month, day, hour, minute, second, and milliseconds.
Contact Us