当サイトではアフィリエイトプログラムを利用しています

Date関数で2つの時間差から期間を求める

javascript

最初に2つの時間差を計算、期間を求める。
次に日を秒に分割、一定単位未満は省略
コードは非常に単純

new Date()の引数は4種類。

new Date();
new Date(year, month, day, hour, minutes, seconds, milliseconds);//month移行省略可能
new Date(value);
new Date(string);

スクリプトの実行時間を表示するため、value,stringのみ行います。年月でやることも可能。


function getDuration(start, end) {
    const ds = new Date(end).getTime() / 1000 - new Date(start).getTime() / 1000;
    if (!ds || ds < 0) return '0秒';
    let ls, rStr = '';
    rStr += ds / 86400 > 1 ? Math.floor(ds / 86400) + '日' : '';
    ls = ds % 86400;
    rStr += ls / 3600 > 1 ? Math.floor(ls / 3600) + '時' : '';
    ls = ds % 3600;
    rStr += ls / 60 > 1 ? Math.floor(ls / 60) + '分' : '';
    ls = ds % 60;
    rStr += ls + '秒';
    return rStr;
}

console.log(getDuration(4250000000,5800000000));
console.log(getDuration('2022/10/24','2022/12/24'));
console.log(getDuration('2022-10-24','2022-12-24'));
PVアクセスランキング にほんブログ村
ブログランキング・にほんブログ村へ
タイトルとURLをコピーしました