![]() |
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 We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using String ManipulationThis approach involves splitting the input string using the delimiter, extracting the hour and minute components, and converting them to a 24-hour format. Syntax: const [time, period] = timeString.split(' '); Example: In this example, we are using the above approach.
Output 15:30 Approach 2: Using Regular ExpressionsRegular expressions can help extract the hour, minute, and AM/PM components from the input string. The AM/PM component is then used to adjust the hour value. Syntax: const match = timeString.match(/(\d+):(\d+) (\w+)/); Example: In this example Regular expressions split time into hour, minute, and period. Adjust hour based on period to 24-hour format. Combine components into a formatted string.
Output 16:45 Approach 3: Using the Date ObjectIn this approach, using the Date object, input time is set with a common date. The formatted time is extracted in 24-hour format using toLocaleTimeString. Syntax: let formattedTime = date.toLocaleTimeString('en-US', { hour12: false }); Example: In this approach we are using the above-explained approach.
Output 21:15:00 Approach 4: Using Moment.js LibraryMoment.js is a popular library for parsing, validating, manipulating, and formatting dates and times in JavaScript. We can leverage its functionality to easily convert a string to 24-hour time format. First, you need to include the Moment.js library in your project. You can do this by either downloading the library and adding it to your project or using a package manager like npm to install it. Once Moment.js is included in your project, you can use its parsing and formatting capabilities to convert the input string to 24-hour time format. Example:
Output 16:30 Approach 5: Using Intl.DateTimeFormatThe 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.
Output 21:15 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |