Javascript Interview Question String Convert Military Time to Standard Time

Introduction

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

Example:

toStandardTime('13:22') should return '01:22 pm'

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

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

if ( toStandardTime('03:16') === '03:16 am') {
    console.log("Test 1 pass, toStandardTime('03:16') returns '03:16 am'");
    passed += 1;
} else {
    console.log("Test 1 failed, toStandardTime('03:16') should return '03:16 am'");
    failed += 1;
}

if ( toStandardTime('13:22') === '01:22 pm') {
    console.log("Test 2 pass, toStandardTime('13:22') returns '01:22 pm'");
    passed += 1;
} else {
    console.log("Test 2 failed, toStandardTime('13:22') should return '01:22 pm'");
    failed += 1;
}

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



function toStandardTime(militaryTime) {
    var hour = Number(militaryTime.slice(0, 2));
    var minute = militaryTime.slice(3);
    var extension = 'am';

    if (hour > 12) {
        hour -= 12;
        extension = 'pm';
    } else if (hour === 0) {
        hour = 12;
    }

    var standardTime = displayDoubleDigit(hour) + ':' + minute + ' ' + extension;

    return standardTime;
}

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

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

if ( toStandardTime('03:16') === '03:16 am') {
    console.log("Test 1 pass, toStandardTime('03:16') returns '03:16 am'");
    passed += 1;
} else {
    console.log("Test 1 failed, toStandardTime('03:16') should return '03:16 am'");
    failed += 1;
}

if ( toStandardTime('13:22') === '01:22 pm') {
    console.log("Test 2 pass, toStandardTime('13:22') returns '01:22 pm'");
    passed += 1;
} else {
    console.log("Test 2 failed, toStandardTime('13:22') should return '01:22 pm'");
    failed += 1;
}

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



PreviousNext

Related