LoginSignup
1
0

More than 3 years have passed since last update.

【教材】JavaScriptの教材を作ってみました4 〜Dateオブジェクト〜

Last updated at Posted at 2020-12-21

※当方駆け出しエンジニアのため、間違っていることも多々あると思いますので、ご了承ください。また、間違いに気付いた方はご一報いただけると幸いです。

半人前のくせに、偉そうに教材を作ってみました。

学べる技術

  • Dateオブジェクト
  • 配列の操作
  • console.table

問題1

年と月を引数に与えたら、(例: (2010, 10))最終日の曜日を漢字(例:火)でログ出力する関数を作ってください。

回答例
const getDay = (year, nextMonth) => {
  let days = ["", "", "", "", "", "", ""];
  let target = new Date(year, nextMonth, 1 - 1);
  console.log(days[target.getDay()]);
}
  //月は0から起算するため、nextMonthに1を入れた場合2月と判断します。
  //1-1は1日の前日と言う意味です。つまり入力した月の翌月の1日の前日。つまり今月の最終日が取得できます。(もちろん0でもいいです。)
  //getDay();で曜日が取得できます。0〜6で返る。日曜日が0。

問題2

異なる2つの年月日を引数(例:("2010-04-08","2020-12-21"))にとり、その間が何日間であるかをログ出力する関数を作ってください。

回答例
const getDate = (day1, day2) => {
  let Day1 = new Date(day1);
  let Day2 = new Date(day2);
  console.log((Day2.getTime() - Day1.getTime()) / (1000 * 60 * 60 * 24));
}


//getTime関数は、1970年1月1日0時0分0秒からの経過ミリ秒を返します。
//2日間の、経過ミリ秒の差を出してから、1000ミリ秒*60秒*60分*24時間で割って日数に直します。

問題3

make_calendar関数に月を引数に与えたら、(例:  make_calendar(2020, 12) )下記のようにカレンダー風にログ出力するプログラムを作成してください。

image.png

回答例

const day = ["", "", "", "", "", "", ""]; //初期配列

const preMonth = (firstDay) => { //1日より前の部分作成
  for (let i = 0; i < firstDay; i++) { //今月の初日の曜日の数値回ループ 例:火曜なら2
    day.push('');//初期配列に ''を追加
  }
}

const toMonth = (lastDate) => { //今月部分作成
  for (let i = 0; i < lastDate; i++) { //今月の最終日回繰り返す
    day.push(i + 1);//初期配列に 1から今月の最終日まで追加
  }
}

const getDay = (target) => { //曜日取得関数
  return target.getDay();
}

const make_calendar = (year, month) => { //本体

  const firstDate = new Date(year, month - 1, 1);//今月の初日取得
  const lastDate = new Date(year, month, 0);//最終日取得

  preMonth(firstDate.getDay()); //引数は初日の曜日。
  toMonth(lastDate.getDate());  //引数は最終日の日付。

  const num = Math.floor(day.length / 7); //ループ回数を決定

  const calendar = []

  for (let i = 0; i < num + 1; i++) { //numは切り捨てられてるため+1
    calendar.push(day.splice(0, 7));//7個づつ切り出して、push
  }
  console.table(calendar); //console.tableで二次元配列をテーブル表示
}

※回答例はあくまで一例です。あまり鵜呑みにしないでください。

1
0
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
1
0