2

I had this test:

Implement an function toReadableString(int) that takes an integer that represents number of seconds
from 00:00:00 and returns a printable string format with AM / PM notation.
For ex.
01:00:00 = 3600
07:00:00 = 25200
toReadableString(3600) should return "1:00AM"
toReadableString(25200) should return "7:00AM"

And my solution is:

function padZero(string){
  return ("00" + string).slice(-2);
}
function toReadableString(time) {
  var hrs = ~~(time / 3600 % 24),
      mins = ~~((time % 3600) / 60),
      timeType = (hrs>11?"PM":"AM");
  return hrs + ":" + padZero(mins) + timeType;
}

But it fails most of test cases. The test cases are hidden, so I don't know why i failed the test. I have tried most of the test cases I could think of. Any ideas what's wrong with my solution?

7
  • toReadableString(0) returns "0:00AM" Commented Jul 20, 2017 at 6:21
  • toReadableString(1) returns "0:00AM" Commented Jul 20, 2017 at 6:21
  • I am not convinced this is what you expect Commented Jul 20, 2017 at 6:21
  • @eddyP23 But it fails most of test cases.....It is mentioned in the question post. Commented Jul 20, 2017 at 6:22
  • What about negative numbers? Commented Jul 20, 2017 at 6:25

2 Answers 2

3

Your hours are between 0 and 24 (where 0 and 24 are actually 12:00AM)

function toReadableString(time) {
  if (time < 0)
    time = 0;
  var hrs = ~~(time / 3600 % 24),
    mins = ~~((time % 3600) / 60),
    timeType = (hrs > 11 ? "PM" : "AM");
  if (hrs > 12)
    hrs = hrs - 12;
  if (hrs == 0)
    hrs = 12;
  return hrs + ":" + padZero(mins) + timeType;
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh yes you are right, I didn't consider 12 and > 12, no one says 14:00 PM, that's how I failed the test.
0
String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

You can use it now like:

alert("5678".toHHMMSS());

1 Comment

what about meridiems?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.