javascript算法题

已知两个时间戳a,b,单位ms

把它们的差值转换成 x天x小时x分钟

如何设计该算法,可以将误差降至最低呢?

阅读 3.9k
4 个回答
function timediff(a, b) {
    var delta = Math.round(Math.abs(a - b) / (1000 * 60));// 相差分钟数
    var day = Math.floor(delta / (60 * 24)); // 天
    delta %= (60 * 24);
    var hour = Math.floor(delta / 60); // 小时
    delta %= 60;
    var minute = delta; // 分钟
    
    return [day, '天', hour, '小时', minute, '分钟'].join('');
}

function timediff2(a, b) {
    var fragments = [];
    var delta = Math.round(Math.abs(a - b) / (1000 * 60));// 相差分钟数
    var day = Math.floor(delta / (60 * 24)); // 天
    delta %= (60 * 24);
    if (day > 0) {
        fragments.push(day, '天');
    }
    var hour = Math.floor(delta / 60); // 小时
    delta %= 60;
    if (hour > 0) {
        fragments.push(hour, '小时');
    }
    
    var minute = delta; // 分钟
    fragments.push(minute, '分钟');
    
    return fragments.join('');
}

为什么会有误差?

diff = Math.abs(a - b);
now = new Date();
time = new Date(now.getTime() + diff);
diffDays = time.getDate() - now.getDate();
diffHours = time.getHours() - now.getHours();
diffMinutes = time.getMinutes() - now.getMinutes();

function timeInterval(a, b) {
    var result = null;
    var differMin = Math.floor(Math.abs(a - b) / 1000 / 60);
    var differHour = Math.floor(differMin / 60);

    var day = Math.floor(differHour / 24);
    var hour = differHour - day * 24;
    var minute = differMin - differHour * 60;

    result = day + "天" + hour + "小时" + minute + "分钟";
    return result;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题