index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="MyDate.js" type="text/javascript"></script>
<title>今日の日付を表示する</title>
<style> #today{ font-size: 24pt; } </style>
<script type="text/javascript">
// 起動時の処理
window.addEventListener("load", function(){
// MyDateクラスをインスタンス化
let date = new MyDate();
// id:todayのタグに今日の日付を表示する
document.getElementById("today").innerHTML = date.getToday();
});
</script>
</head>
<body>
<h1>今日の日付を表示する</h1>
<div id="today"></div>
</body>
</html>
MyDate.js
/* 日付クラス*/
class MyDate{
// コンストラクタ
constructor(){
let myDate = new Date();
this.year = myDate.getFullYear();
this.month = myDate.getMonth() + 1;
this.date = myDate.getDate();
const week = ["日", "月", "火", "水", "木", "金", "土"];
this.day = week[myDate.getDay()];
}
// メソッド
getYear(){ // 年を返す
return this.year;
}
getMonth(){ // 月を返す
return this.month;
}
getDate(){ // 日を返す
return this.date;
}
getDay(){ // 曜日を返す
return this.day;
}
getToday(){ // 「2020年7月24日(水)」の形式で返す
return (this.year + "年" + this.month + "月" + this.date + "日" + "(" + this.day + ")" );
}
}