How to use the Intl.DateTimeFormat() Constructor In Javascript
The Intl.DateTimeFormat() constructor is a built-in JavaScript object that enables language-sensitive date and time formatting. By specifying the desired locale and format options, we can obtain the formatted date in the desired format.
Syntax:
const formattedDate = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(today);
Parameters:
- ‘en-GB’: Specifies the locale as English (United Kingdom). This ensures that the date format is dd/mm/yyyy.
- { day: ‘2-digit’, month: ‘2-digit’, year: ‘numeric’ }: Specifies the format options for the date. ‘2-digit’ ensures that both the day and month are displayed as two digits, and ‘numeric’ ensures that the year is displayed as a numeric value.
Return Value:
The return value of this method is a string representing the formatted date according to the specified locale and options.
Example 1: This example format the date in dd/mm/yyyy by checking both date and month, If they are not in 2 digits the zero is added to make them 2 digits.
let today = new Date();
console.log(today);
let dd = today.getDate();
let mm = today.getMonth() + 1;
let yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
console.log(today);
Output
2023-12-15T09:43:41.117Z 15/12/2023
Example 2: This example first slice the date part from the date object and then format the date in dd/mm/yyyy.
let today = new Date();
console.log(today);
function gfg_Run() {
let date = today.toJSON().slice(0, 10);
let nDate = date.slice(8, 10) + '/'
+ date.slice(5, 7) + '/'
+ date.slice(0, 4);
console.log(nDate);
}
gfg_Run();
Output
2023-12-15T09:43:41.245Z 15/12/2023
Example 3:
function formatCurrentDate() {
const today = new Date();
const options = { day: '2-digit', month: '2-digit', year: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-GB', options);
const formattedDate = formatter.format(today);
console.log(formattedDate);
}
formatCurrentDate();
Output
26/05/2024
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
How to get current formatted date dd/mm/yyyy in JavaScript ?
In this article, we will see how to get the format current date in dd/mm/yyyy format by using JavaScript. We’re going to discuss a few methods. The first few methods to know.
These are the methods that can be used in solving this problem:
Table of Content
- JavaScript getDate() Method
- JavaScript getFullYear() Method
- JavaScript getMonth() Method
- JavaScript String slice() method
- JavaScript replace() method