代码之家  ›  专栏  ›  技术社区  ›  Martin Brandt

将数字转换为时间(mm:ss)

  •  0
  • Martin Brandt  · 技术社区  · 2 年前

    我想使用一个脚本将列B2:B(文本格式)转换为分钟和秒(mm:ss)。我可以用公式(=B2/86400)来实现这一点,但它应该用脚本来实现:

    COLUMN B    (COLUMN B)
    
    244         (= 04:04)
    211         (= 03:31)
    229         (= 03:49)
    246         (= 04:06)
    

    我该怎么做?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Eldiyar    2 年前

    您可以使用Google Sheets中的Google Apps脚本实现此转换。下面是一个脚本,它将B列中的数字转换为分秒格式(mm:ss),并填充C列中的相邻单元格:

    function convertToTime() {
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      const range = sheet.getRange('B2:B' + sheet.getLastRow());
      const values = range.getValues().map(([seconds]) => {
        const minutes = Math.floor(seconds / 60);
        const paddedSeconds = seconds % 60 < 10 ? '0' : '';
        return `${minutes}:${paddedSeconds}${seconds % 60}`;
      });
      range.setValues(values);
    }

    确保B列只包含表示秒数的数字。如果有任何非数字值,脚本将抛出一个错误。

        2
  •  0
  •   Smuuuu    2 年前

    您可以缩短填充的“秒”部分:

      const paddedSeconds = (seconds % 60).toString().padStart(2, "0");