gas ミリ秒を秒、分、時間、日にちに変換

GAS

時間の換算単位

  //時間換算用の変数
  //1秒=1000ミリ秒
  var seconds = 1000;
  //1分=1000ミリ秒×60秒
  var minutes = 1000 * 60;
  //1時間=1000ミリ秒×60秒×60分
  var hours = 1000 * 60 * 60;
  //1日=1000ミリ秒×60秒×60分×24時間
  var days = 1000 * 60 * 60 * 24;
  //1年=1000ミリ秒×60秒×60分×24時間×365日
  var years = 1000 * 60 * 60 * 24 * 365;

例1

function sample1() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('シート1');

  const startTime = sheet.getRange('A1').getValue();         // 開始時刻を取得
  const endTime = sheet.getRange('B1').getValue();           // 終了時刻を取得
  const duration = endTime.getTime() - startTime.getTime();  // 時間を算出(ミリ秒単位)

  const hours = Math.floor(duration / 3600000);                                      // 時
  const minutes = Math.floor((duration - hours * 3600000) / 60000);                  // 分
  const seconds = Math.floor((duration - hours * 3600000 - minutes * 60000) / 1000); // 秒

  sheet.getRange('C1').setValue(`${hours}:${minutes}:${seconds}`);  // セルに書き込み
}

例2

function sample2() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('シート1');

  const startTime = sheet.getRange('A1').getValue();         // 開始時刻を取得
  const endTime = sheet.getRange('B1').getValue();           // 終了時刻を取得
  const diff = endTime.getTime() - startTime.getTime();  // 時間を算出(ミリ秒単位)

  const diff_seconds = Math.floor(diff/1000)%60;    // 秒の計算
  const diff_minutes =Math.floor(diff/1000/60)%60;  // 余りから分の計算
  const diff_hours =Math.floor(diff/1000/60/60)%24; // 余りから時間の計算
  const diff_days =Math.floor(diff/1000/60/60/24);  // 余りから日数の計算

  sheet.getRange('C1').setValue(`${diff_days}日 ${diff_hours}時${diff_minutes}分${diff_seconds}秒`);  // セルに書き込み
}

結果

image.png

コメント