如何以“类似时钟的方式”添加数字?

问题描述 投票:0回答:2

我目前正在将小时数作为数字,例如2230等于22:30。我希望能够向其添加数字并求和,就像将它们加到小时中一样。

2030 + 60 = 2130 //and not 2090
2330 + 120 = 0230 //and not 2350

是否有执行此操作的库或函数?还是我应该更改处理时间的方式?

javascript
2个回答
2
投票

我不建议这样做,但是如果您想这样做,您必须处理一个事实,即您假装一个小时为100分钟。您可以通过从假值中提取真实的小时和分钟,对它们进行数学运算,然后重新组合它们,来完成这些工作:

function toHoursAndMinutes(value) {
    // Get hours: `value` divided by 100
    const hours = Math.floor(value / 100);
    // Get minutes: the remainder of dividing by 100
    const minutes = value % 100;
    // Return them
    return [hours, minutes];
}

function fromHoursAndMinutes(hours, minutes) {
    // Reassemble the number where hours are worth 100
    return hours * 100 + minutes;
}

function add(a, b) {
    // Get `a`'s hours and minutes
    const [ahours, aminutes] = toHoursAndMinutes(a);
    // Get `b`'s
    const [bhours, bminutes] = toHoursAndMinutes(b);
    // Add the hours together, plus any from adding the minutes
    const hours = ahours + bhours + Math.floor((aminutes + bminutes) / 60);
    // Add the minutes together, ignoring extra hours
    const minutes = (aminutes + bminutes) % 60;
    // Reassemble
    return fromHoursAndMinutes(hours, minutes);
}

实时示例:

function toHoursAndMinutes(value) {
    // Get hours: `value` divided by 100
    const hours = Math.floor(value / 100);
    // Get minutes: the remainder of dividing by 100
    const minutes = value % 100;
    // Return them
    return [hours, minutes];
}

function fromHoursAndMinutes(hours, minutes) {
    // Reassemble the number where hours are worth 100
    return hours * 100 + minutes;
}

function add(a, b) {
    // Get `a`'s hours and minutes
    const [ahours, aminutes] = toHoursAndMinutes(a);
    // Get `b`'s
    const [bhours, bminutes] = toHoursAndMinutes(b);
    // Add the hours together, plus any from adding the minutes
    const hours = ahours + bhours + Math.floor((aminutes + bminutes) / 60);
    // Add the minutes together, ignoring extra hours
    const minutes = (aminutes + bminutes) % 60;
    // Reassemble
    return fromHoursAndMinutes(hours, minutes);
}

console.log(add(2030, 60));
console.log(add(2330, 120));

但是再次,我不建议这样做。相反,请使用时间值(Date或自Epoch以来的毫秒数等),并在需要显示时进行转换以进行显示。


0
投票

这是我的实现方式

function add(current, time) {
    const hours = Math.floor(time / 60);
    const minutes = time % 60;
    const currentMinutes = parseInt(current.toString().slice(2));
    const currentHours = parseInt(current.toString().slice(0, 2));
    const newMinutes = (currentMinutes + minutes) % 60;
    const additionalHours = (currentMinutes + minutes) > 60 ? 1 : 0;
    const newHours = (currentHours + hours + additionalHours) % 24;


    return `${newHours < 10 ? '0' : ''}${newHours}${newMinutes < 10 ? '0' : ''}${newMinutes}`;
}

console.log(add(2030, 60)); // 2130
console.log(add(2330, 120)); // 0130

© www.soinside.com 2019 - 2024. All rights reserved.