
- 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
Rectifying the time string in JavaScript
Problem
We are required to write a JavaScript function that takes in a time string in “HH:MM:SS” format.
But there was a problem in addition, so many of the time strings are broken which means the MM part may exceed 60, and SS part may as well exceed 60.
Our function should make required changes to the string and return the new rectified string.
For instance −
"08:11:71" -> "08:12:11"
Example
Following is the code −
const str = '08:11:71'; const rectifyTime = (str = '') => { if(!Boolean(str)){ return str; }; const re = /^(\d\d):(\d\d):(\d\d)$/; if (!re.test(str)){ return null; }; let [h, m, s] = str.match(re).slice(1,4).map(Number); let time = h * 3600 + m * 60 + s; s = time % 60; m = (time / 60 |0) % 60; h = (time / 3600 |0) % 24; return [h, m, s] .map(String) .join(':'); }; console.log(rectifyTime(str));
Output
Following is the console output −
08:12:11
- Related Articles
- Merging and rectifying arrays in JavaScript
- Add time to string data/time - JavaScript?
- Forming the nearest time using current time in JavaScript
- Finding the time elapsed in JavaScript
- JavaScript Program for Queries for rotation and Kth character of the given string in constant time
- Convert string of time to time object in Java
- How to Convert Time String to Time in Excel?
- Hyphen string to camelCase string in JavaScript
- Repeat String in JavaScript?
- Compressing string in JavaScript
- Can the string be segmented in JavaScript
- Parse string date time value input in Java
- How to convert string to time in MySQL?
- How to set current time to some other time in JavaScript?
- How do I trigger a function when the time reaches a specific time in JavaScript?

Advertisements