Rectifying the time string in JavaScript

In JavaScript, we often need to rectify invalid time strings where the minutes or seconds exceed their maximum values (59). This function converts an invalid time format like "08:11:71" into a valid one by carrying over excess values to the next time unit.

Problem

We need to write a JavaScript function that takes in a time string in "HH:MM:SS" format. However, many time strings are broken, meaning the MM part may exceed 60, and SS part may exceed 60 as well. Our function should make required changes and return the rectified string.

For instance:

"08:11:71" -> "08:12:11"

How It Works

The algorithm converts the time to total seconds, then redistributes the time correctly across hours, minutes, and seconds:

  1. Parse the input string into hours, minutes, and seconds
  2. Convert everything to total seconds
  3. Extract correct seconds (remainder when divided by 60)
  4. Extract correct minutes (remainder when divided by 60 after converting to minutes)
  5. Extract correct hours (with 24-hour wraparound)

Example

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);
    
    // Convert to total seconds
    let time = h * 3600 + m * 60 + s;
    
    // Extract corrected values
    s = time % 60;
    m = (time / 60 | 0) % 60;
    h = (time / 3600 | 0) % 24;
    
    // Format back to HH:MM:SS
    return [h, m, s]
        .map(val => val.toString().padStart(2, '0'))
        .join(':');
};

console.log(rectifyTime(str));
console.log(rectifyTime('23:59:61')); // Test case with minute overflow
console.log(rectifyTime('12:75:30')); // Test case with hour overflow
08:12:11
00:00:01
13:15:30

Step-by-Step Breakdown

Let's trace through the example "08:11:71":

const input = '08:11:71';
let [h, m, s] = [8, 11, 71]; // Parsed values

// Convert to total seconds
let totalSeconds = 8 * 3600 + 11 * 60 + 71;
console.log('Total seconds:', totalSeconds); // 29531

// Extract corrected values
let correctedS = totalSeconds % 60;
console.log('Corrected seconds:', correctedS); // 11

let correctedM = Math.floor(totalSeconds / 60) % 60;
console.log('Corrected minutes:', correctedM); // 12

let correctedH = Math.floor(totalSeconds / 3600) % 24;
console.log('Corrected hours:', correctedH); // 8
Total seconds: 29531
Corrected seconds: 11
Corrected minutes: 12
Corrected hours: 8

Enhanced Version with Error Handling

const rectifyTimeEnhanced = (str = '') => {
    // Handle empty or null input
    if (!str || typeof str !== 'string') {
        return null;
    }
    
    // Validate format
    const timeRegex = /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    const match = str.match(timeRegex);
    
    if (!match) {
        throw new Error('Invalid time format. Expected HH:MM:SS');
    }
    
    let [, hours, minutes, seconds] = match.map(Number);
    
    // Convert to total seconds
    const totalSeconds = hours * 3600 + minutes * 60 + seconds;
    
    // Calculate corrected values
    const correctedSeconds = totalSeconds % 60;
    const correctedMinutes = Math.floor(totalSeconds / 60) % 60;
    const correctedHours = Math.floor(totalSeconds / 3600) % 24;
    
    // Format with leading zeros
    return [correctedHours, correctedMinutes, correctedSeconds]
        .map(val => val.toString().padStart(2, '0'))
        .join(':');
};

// Test cases
console.log(rectifyTimeEnhanced('08:11:71'));
console.log(rectifyTimeEnhanced('1:5:90'));
console.log(rectifyTimeEnhanced('25:65:125'));
08:12:11
01:06:30
02:07:05

Key Points

  • The function handles time overflow by converting to total seconds
  • Hours wrap around at 24 (24:00:00 becomes 00:00:00)
  • The bitwise OR operator (|0) is used for fast integer conversion
  • padStart() ensures two-digit formatting for the output

Conclusion

This time rectification function converts invalid time strings to valid format by handling overflow in seconds and minutes. It's useful for processing time data from unreliable sources or user input validation.

Updated on: 2026-03-15T23:19:00+05:30

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements