代码之家  ›  专栏  ›  技术社区  ›  espresso_coffee

如何替换字符串中的时间戳和整小时?

  •  2
  • espresso_coffee  · 技术社区  · 6 年前

    0600-2200 MAY 15-SEP 30; 0600-2100 OCT 1-MAY 14 . 我有一个函数,它在字符串中查找时间戳并返回小时数。返回数组的示例如下所示: [16,15] . 该数组有两个值,我需要替换 0600-2200 16 然后加上这个词 hours 对那件事。因此,最终输出应如下所示: 16 hours MAY 15-SEP 30; 15 hours OCT 1-MAY 14 . 以下是将时间戳转换为字符串的函数示例:

    var timeSt = "0600-2200 MAY 15-SEP 30; 0600-2100 OCT 1-MAY 14";
    const calcDifference = range => {
        const time = range.split`-`.map(e => (+e.substr(0, 2) * 60 + (+e.substr(2))) / 60);
        return time[1] - time[0];
    };
    
    const diffs = timeSt.match(/\d{4}\-\d{4}/g).map(e => calcDifference(e));
    console.log(diffs);

    我尝试过的解决方案如下所示:

    var hours = "";
    for(var i=0; i < diffs.length; i++){
        hours += timeSt.replace(regex,diffs[i] + " hours ");
    }
    

    以下是上述示例产生的输出:

    16 hours MAY 15-SEP 30; 16 hours OCT 1-MAY 1415 hours MAY 15-SEP 30; 15 hours OCT 1-MAY 14

    似乎整个字符串被附加了两次。我理解为什么会发生这种情况,但仍然无法找到解决此问题的好方法。我注意到的另一件事是,一些时间戳值如下所示: 0000 - 2359

    在这种情况下,转换小时数的函数将返回: [23.983333333333334] 24 这是唯一一种将值四舍五入的情况 法官对他的案子提出了更高的要求。I时间戳如下所示: 0500-2330 函数返回 [18.5]

    1 回复  |  直到 6 年前
        1
  •  3
  •   Dmitriy    6 年前

    对于替换问题,您可以向 .replace 函数的字符串形式。

    const roundMinutes = 15;
    const timeSt = "0600-0000 MAY 15-SEP 30; 0600-2145 OCT 1-MAY 14";
    
    const calcDifference = range => {
      const time = range.split`-`.map(e => +e.substr(0, 2) * 60 + (+e.substr(2)));
      let [start, end] = time;
      if (end < start) {
        end += 24 * 60;
      }
      return end - start;
    };
    
    const formatted = timeSt.replace(/\d{4}\-\d{4}/g, (range) => {
      const diff = calcDifference(range);
      const full = Math.round(diff / roundMinutes) * roundMinutes;
      const hours = Math.floor(full / 60);
      const minutes = full - hours * 60;
      const time = minutes === 0 ? `${hours}` : `${hours}.${minutes}`
      return `${time} hours`;
    })
    
    console.log(formatted)
    

    要更改精度,可以调整 roundMinutes