JavaScriptで今週の月曜日と日曜日の年月日+曜日 を取得するメソッド



アクセスした時点での週の始まりと終わりを返すメソッドです。

2018年12月31日 (月) ~ 2019年1月6日 (日) という形になります。

      formedDateOfThisWeek(){
        let today = new Date();
        let this_year = today.getFullYear();
        let this_month = today.getMonth();
        let date = today.getDate();
        let day_num = today.getDay();
        let this_monday = date - day_num + 1;
        let this_sunday = this_monday + 6;
        let day = new String('日月火水木金土');

        //月曜日の年月日
        let start_date = new Date(this_year, this_month, this_monday);
            start_date = start_date.getFullYear() + "年" + (start_date.getMonth() + 1) + "月" + start_date.getDate() + "日" + " (" + day.charAt( start_date.getDay() ) + ")"
        //日曜日の年月日
        let end_date = new Date(this_year, this_month, this_sunday);
            end_date =  end_date.getFullYear() + "年" + (end_date.getMonth() + 1) + "月" + end_date.getDate() + "日" + " (" + day.charAt( end_date.getDay() ) +")"
        //文字列を作成
        let target_week = start_date + " ~ " + end_date;
        return target_week
      }



Date.getDay()メソッドは指定された日付の曜日を数字で返します。
0(日曜日)~6(土曜日)という形。


date - day_num + 1;
で今日の日付からday_numを引くことで当週の日曜日の日付を取得し、さらに1を足して当週の月曜日の日付を取得し、変数this_mondayに格納します。


start_date = start_date.getFullYear() + "年" + (start_date.getMonth() + 1) + "月" + start_date.getDate() + "日" + " (" + day.charAt( start_date.getDay() ) + ")"

ここの最後の曜日を返す部分は、月曜日と日曜日と決まっているのでそのまま入力しても良かったんですが、ちょっと練習ということでやってみました。


String.charAt(引数) String文字列の(引数)番目の値を取り出し、その値のみで構成された文字列を返します。
String('日月火水木金土');に対して.charAtを実行し、引数に( start_date.getDay() )を指定することで1番目の「月」という文字列を返しています。