How to Format Dates in JavaScript with One Line of Code

To format dates in JavaScript with one line of code, you can use the toLocaleDateString() method. This method returns a string representing the date portion of a Date object based on the user’s local time zone and formatting preferences.

Here’s an example code snippet:

const date = new Date();
const formattedDate = date.toLocaleDateString('en-US'); // Change 'en-US' to your preferred locale
console.log(formattedDate); // Output: "2/16/2023" (if today's date is Feb 16, 2023)

In this example, we create a new Date object representing the current date and time. We then call the toLocaleDateString() method on this object, passing in the desired locale (in this case, ‘en-US’) as a parameter. The method returns a formatted string representing the date portion of the Date object, using the specified locale’s formatting conventions.

By default, the toLocaleDateString() method uses the browser’s current locale settings. However, you can pass in a specific locale code as a parameter to format the date according to that locale’s conventions. You can also pass in additional options as a second parameter to customize the formatting further, such as the date style, time zone, and calendar type.