Javascript整数到时间字符串

Javascript整数到时间字符串,javascript,time,Javascript,Time,我做了这个测试: 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) sh

我做了这个测试:

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"
我的解决方案是:

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;
}

但大多数测试用例都失败了。测试用例是隐藏的,所以我不知道为什么我没有通过测试。我已经尝试了我能想到的大多数测试用例。你知道我的解决方案有什么问题吗?

你的工作时间在0到24小时之间(其中0到24小时实际上是12:00AM)

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;
}
函数到可读取字符串(时间){
如果(时间<0)
时间=0;
变量小时数=~(时间/3600%24),
分钟=~((时间%3600)/60),
时间类型=(小时>晚上11点):“上午”;
如果(小时数>12)
hrs=hrs-12;
如果(小时==0)
hrs=12;
返回小时数+“:”+padZero(分钟)+时间类型;
}

toReadableString(0)返回“0:00AM”toReadableString(1)返回“0:00AM”我不相信这是您想要的expect@eddyP23但是大多数测试用例都失败了……这是在问号中提到的。负数呢?什么是经线?哦,是的,你是对的,我没有考虑12和12,没有人说下午14:00。这就是我考试失败的原因。
alert("5678".toHHMMSS());
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;
}