0
1

More than 1 year has passed since last update.

JavaScript 日付フォーマット、日時分秒の差分計算(週末・年末まで)

Last updated at Posted at 2023-02-14

JavaScript の日付処理でさっとやったやつをメモしておく
フォーマット、日付計算とかもっと良いのないかなと感じてます...
変数名も適当すぎる...

// 現在日時取得
const now = new Date();
// 今週末
const nextWeekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - now.getDay()));
// 来年初日
const nextYearFirst = new Date(now.getFullYear() + 1, 0, 1);

console.log(dateFormat(now));
console.log(diffDate(now, nextWeekEnd));
console.log(diffDate(now, nextYearFirst));
console.log(diffTimes(now, nextWeekEnd));
console.log(diffTimes(now, nextYearFirst));

// 曜日の日本語リスト
//const weekdays = ['日', '月', '火', '水', '木', '金', '土'];

// 日付フォーマット YYYY/MM/DD(a)HH:MI:SS
function dateFormat(date) {
    const formatOptions = {
        year: "numeric", month: "2-digit", day: "2-digit", weekday: 'short'
        , hour: "2-digit", minute: "2-digit", second: "2-digit"
    }
    return date.toLocaleString("ja-JP", formatOptions);
    // return date.toLocaleString("sv-SE").replace(' ', `(${weekend[date.getDay()]})`);
    // return date.getFullYear() + '/'
    //     + String(date.getMonth() + 1).padStart(2, '0') + '/'
    //     + String(date.getDate()).padStart(2, '0') + '('
    //     + weekend[date.getDay()] + ')'
    //     + String(date.getHours()).padStart(2, '0') + ':'
    //     + String(date.getMinutes()).padStart(2, '0');
}

// 日時の日数差
function diffDate(from, to) {
    const f = new Date(from.getFullYear(), from.getMonth(), from.getDate());
    const t = new Date(to.getFullYear(), to.getMonth(), to.getDate());
    return Math.floor((t.getTime() - f.getTime()) / (1000 * 60 * 60 * 24));
}

// 日時の時分秒差
function diffTimes(from, to) {
    const diffTime = to.getTime() - from.getTime();
    return {
        time: diffTime,
        hour: Math.floor(diffTime / (1000 * 60 * 60)),
        minute: Math.floor(diffTime / (1000 * 60)),
        Second: Math.floor(diffTime / 1000)
    }
}

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1