Using the Date Object
toLocaleDateString() method returns a string representing the date portion of a Date object according to the browser’s local conventions. It takes optional parameters for customizing the formatting options, such as the locale and timezone.
const date = new Date(); const formattedDate = date.toLocaleDateString('en-US'); console.log(formattedDate); // Output: 7/10/2023
toLocaleTimeString() method returns a string representing the time portion of a Date object, respecting the browser’s local conventions.
const date = new Date(); const formattedTime = date.toLocaleTimeString('en-US'); console.log(formattedTime); // Output: 10:30:45 AM
toLocaleString() method combines the date and time portions of a Date object into a single string, respecting the browser’s local conventions.
const date = new Date(); const formattedDateTime = date.toLocaleString('en-US'); console.log(formattedDateTime); // Output: 7/10/2023, 10:30:45 AM
Using External Libraries
To get started with Moment.js, you need to include the library in your project. You can download it from the official website or use a package manager like npm.
// Include Moment.js in your HTML file before using it const date = moment(); const formattedDate = date.format('YYYY-MM-DD'); console.log(formattedDate); // Output: 2023-07-10
Similar to Moment.js, you need to include Luxon in your project before using it. You can download it from the official website or install it via npm.
// Include Luxon in your HTML file before using it const DateTime = luxon.DateTime; const date = DateTime.now(); const formattedDate = date.toFormat('yyyy LLL dd'); console.log(formattedDate); // Output: 2023 Jul 10