Horje
How to Format Dates in JavaScript with One Line of Code?

In order to format dates, a Date object must be transformed into a string representation that follows to a predefined format. JavaScript simplifies this procedure with its built-in methods and updated APIs. We’ll explore at both older, more cumbersome formats for dates as well as more recent, simpler ones.

These are the following approaches:

Using toLocaleDateString()

The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of this date.

Syntax:

dateObj.toLocaleDateString(locale, options);

Example: This code gets the current date and formats it into a readable string in the format “Month Day, Year” (e.g., “June 20, 2024”).

JavaScript
console.log(new Date()
    .toLocaleDateString('en-US',
        { year: 'numeric', month: 'long', day: 'numeric' }));

Output
July 1, 2024

Using Date.prototype.toISOString()

The toISOString() method returns a date string formatted according to the ISO 8601 extended format.

Syntax:

dateObj.toISOString();

Example: This code gets the current date and time and formats it into an ISO 8601 string format (e.g., “2024-06-21T12:34:56.789Z”).

JavaScript
console.log(new Date().toISOString());

Output
2024-07-01T10:10:01.334Z



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Explain the Concepts of Service Workers in PWAs Explain the Concepts of Service Workers in PWAs
Sorted Linked List to Balanced BST using JavaScript Sorted Linked List to Balanced BST using JavaScript
LRU Cache using JavaScript LRU Cache using JavaScript
How to Add a Line Break in JavaScript? How to Add a Line Break in JavaScript?
Find the Sum of All Left Leaves in a Given Binary Tree using JavaScript Find the Sum of All Left Leaves in a Given Binary Tree using JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17