
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Converting 12 hour format time to 24 hour format in JavaScript
We are required to write a JavaScript function that takes in a time string in the following format −
const timeStr = '05:00 PM';
Note that the string will always be of the same format i.e.
HH:MM mm
Our function should make some computations on the string received and then return the corresponding 24 hour time in the following format: HH:MM
For example:
For the above string, the output should be −
const output = '17:00';
Example
The code for this will be −
const timeStr = '05:00 PM'; const secondTimeStr = '11:42 PM'; const convertTime = timeStr => { const [time, modifier] = timeStr.split(' '); let [hours, minutes] = time.split(':'); if (hours === '12') { hours = '00'; } if (modifier === 'PM') { hours = parseInt(hours, 10) + 12; } return `${hours}:${minutes}`; }; console.log(convertTime(timeStr)); console.log(convertTime(secondTimeStr));
Output
And the output in the console will be −
17:00 23:42
- Related Articles
- Python program to convert time from 12 hour to 24 hour format
- C++ program to convert time from 12 hour to 24 hour format
- C# program to convert time from 12 hour to 24 hour format
- Convert time from 24 hour clock to 12 hour clock format in C++
- How to Convert Time Format from 12 Hour to 24 Hour and Vice Versa in Excel?
- Java Program to display time in 24-hour format
- Java Program to display Time in 12-hour format
- Format hour in k (1-24) format in Java
- Format hour in kk (01-24) format in Java
- Python Pandas - Format the Period object and display the Time with 24-Hour format
- How to convert 12-hour time scale to 24-hour time in R?
- How to convert string to 24-hour datetime format in MySQL?
- Program to convert hour minutes’ time to text format in Python
- Format hour in HH (00-23) format in Java
- 24-hour time in Python

Advertisements