How to useIntl.DateTimeFormat in Javascript
The Intl.DateTimeFormat object provides a way to format dates and times according to the locale and options specified. This approach involves converting the input time to a Date object and then formatting it to a 24-hour time string using Intl.DateTimeFormat.
Example: In this example, we first create a Date object using the input time string, then format the time using Intl.DateTimeFormat with the locale set to ‘en-GB’ (which uses a 24-hour clock by default) and the options to display the hour and minute in two-digit format.
function convertTo24Hour(timeString) {
let date = new Date(`01/01/2022 ${timeString}`);
let options = { hour: '2-digit', minute: '2-digit', hour12: false };
let formattedTime = new Intl.DateTimeFormat('en-GB', options).format(date);
return formattedTime;
}
let inputTime = '09:15 PM';
let formattedTime = convertTo24Hour(inputTime);
console.log(formattedTime);
Output
21:15
JavaScript Program to Convert String to 24-hour Time Format
We are going to learn about the conversion of a string to a 24-hour time format in JavaScript, converting a string to a 24-hour time format involves transforming a time representation from the traditional 12-hour clock (AM/PM) to the 24-hour clock (00:00 to 23:59).
There are several methods that can be used to convert a string to a 24-hour time format in JavaScript, which are listed below:
Table of Content
- Approach 1: Using String Manipulation
- Approach 2: Using Regular Expressions
- Approach 3: Using the Date Object
- Approach 4: Using Moment.js Library
- Approach 5: Using Intl.DateTimeFormat
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us