LoginSignup
8
7

More than 5 years have passed since last update.

JavaScript,Node.jsで年月日ループを実装する

Last updated at Posted at 2018-10-31

概要

探してもあまり見つからなかったので自分で実装することにしました。
startDateとEndDateの値を変えれば動くようになってるはずです。

準備

moment.jsが必要です。

npmまたはyarnでライブラリを導入できる場合は以下のどちらかのコマンドを使ってインストールしてください。

npm i moment
yarn add moment

コード(古い版)

こちらのコードはやたら長い上に上位互換のものがあるので次の見出しにあるコードを使ったほうが見た目いいです。

const moment = require('moment');

function loopYmd(startDate, endDate){
  const start = moment(startDate);
  const end = moment(endDate);

  let s = {
    year: start.get('year'),
    month: start.get('month') + 1,
    day: start.get('date'),
  };
  let e = {
    year: end.get('year'),
    month: end.get('month') + 1,
    day: end.get('date'),
  };

  for (let y = s.year; y <= e.year; y++) {
    const isStartYear = y === s.year;
    const isEndYear = y === e.year;
    const startMonth = isStartYear ? s.month : 1;
    const endMonth = isEndYear ? e.month : 12;

    console.log(y + '');

    for (let m = startMonth; m <= endMonth; m++) {
      const isStartMonth = m === s.month;
      const isEndMonth = m === e.month;
      const startDay = isStartYear && isStartMonth ? s.day : 1;
      const endDay = isEndYear && isEndMonth ? e.day : getEndDay(y, m);

      console.log(m + '');

      for (let d = startDay; d <= endDay; d++) {
        console.log(d + '');
      }
    }
  }
}

function getEndDay(year, month) {
  const date = String(year) + '-' + String(month);
  return moment(date).endOf('month').get('date');
}

loopYmd('2017-12-01', new Date());

コード(短い最新版)

@myrさん ありがとうございます!
moment.jsに加算すれば全部回せるみたいです。

loopYmd.js
function loopYmd(startDate, endDate) {
    let start = moment(startDate);
    const end = moment(endDate);

    while(start.unix() <= end.unix()) {
        console.log(start.format('YYYY-MM-DD'));
        start.add(1, 'days');
    }
}

loopYmd('2017-12-01', new Date());

おわり

ググってもいい感じのコードがなくて自分で実装したので時間がかかりました
皆さんは僕のコードをコピペして時間を有効に使ってください

追記
頑張って時間かけて実装したらめっちゃ短く書けることが発覚しました
Qiitaに書いてなければ知ることはなかったと思うのでアウトプットしてよかったです

8
7
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
8
7