![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements