Javascript Interview Question String Convert Standard Time to Military Time

Introduction

Given input string representing time in standard format, return the military time equivalent

Example:

toMilitaryTime('11:43 pm') should return '23:43'

Hints

  • you may use Number(string) to convert a string to a number
  • you may also use .toString() to convert a number to a string
function toMilitaryTime(standardTime) {
   //your code here
}
/*  Do not edit below this line */

var line = '****************************************************************';
var passed = 0;/* w ww  . ja  v a2  s .c  o  m*/
var failed = 0;

console.log(line);
console.log('toMilitaryTime UNIT TESTS');
console.log(line);

if ( toMilitaryTime('11:43 pm') === '23:43') {
    console.log("Test 1 pass, toMilitaryTime('11:43 pm') returns '23:43'");
    passed += 1;
} else {
    console.log("Test 1 failed, toMilitaryTime('11:43 pm') should return '23:43'");
    failed += 1;
}

if ( toMilitaryTime('04:22 am') === '04:22') {
    console.log("Test 2 pass, toMilitaryTime('04:22 am') returns '04:22'");
    passed += 1;
} else {
    console.log("Test 2 failed, toMilitaryTime('04:22 am') should return '04:22'");
    failed += 1;
}

console.log(line);
console.log('TOTAL TESTS PASSED: ' + passed );
console.log('TOTAL TESTS FAILED: ' + failed );
console.log(line);


function displayDoubleDigit(number){
    if (number < 10) {
        return '0' + number.toString();
    }else{
        return number.toString();
    }
}

function toMilitaryTime(standardTime) {
    var hour = Number(standardTime.slice(0, 2)) % 12;
    var minute = standardTime.slice(3, 5);
    var extension = standardTime.slice(6);

    if (extension === 'pm') {
        hour += 12;
    }

    var militaryTime = displayDoubleDigit(hour) + ':' + minute;

    return militaryTime;
}

var line = '****************************************************************';
var passed = 0;
var failed = 0;

console.log(line);
console.log('toMilitaryTime UNIT TESTS');
console.log(line);

if ( toMilitaryTime('11:43 pm') === '23:43') {
    console.log("Test 1 pass, toMilitaryTime('11:43 pm') returns '23:43'");
    passed += 1;
} else {
    console.log("Test 1 failed, toMilitaryTime('11:43 pm') should return '23:43'");
    failed += 1;
}

if ( toMilitaryTime('04:22 am') === '04:22') {
    console.log("Test 2 pass, toMilitaryTime('04:22 am') returns '04:22'");
    passed += 1;
} else {
    console.log("Test 2 failed, toMilitaryTime('04:22 am') should return '04:22'");
    failed += 1;
}

console.log(line);
console.log('TOTAL TESTS PASSED: ' + passed );
console.log('TOTAL TESTS FAILED: ' + failed );
console.log(line);



PreviousNext

Related