現在から何日後、何日前の日付を計算します。
1)まず、現在の日付と時刻を new Date()で取得する・・・ var xDay = new Date();
2)取得した日時からgetDate()メソッドを使い何日かを取り出す ・・・ xDay.getDate()
3)取り出した日に計算する日数を加算(減算)する ・・・・xDay.getDate() + 10;
4)setDate()メソッドを使い計算日数を再設定する ・・・xDay.setDate(xDay.getDate() + 10);
5) 4)のままではミリ秒単位の数値が入っているので、年/月/日 形式に変換する
・・・・xDay.toLocaleDateString();
Sample
日(半角整数に限る)
はいつになるか?・・・→
(Dateオブジェクトは「25日+10=35日」でなく、「5日」のように自動的に調整してくれます。月によって30日、31日と異なるが、これも調整してくれる。大変賢いオブジェクトです((^^♪ ・・)
Sample Source......................................................................>>>
<script language="JavaScript"><!--
function NewDay(){
var n = document.getElementById ("txt").value;
var xDay = new Date();
if(document.getElementById ('sele').options[sel.selectedIndex].value
== "ato"){
xDay.setDate(xDay.getDate() + parseInt(n));}
if(document.getElementById ('sele').options[sel.selectedIndex].value
== "mae"){
xDay.setDate(xDay.getDate() - parseInt(n));}
var serchDay = xDay.toLocaleDateString();
alert(serchDay);
}
//--></script>
</head>
<body>
<input type="text" size="5" id="txt">日(半角整数に限る)
<select id="sele" name="sel">
<option value="ato" selected>後
<option value="mae">前
</select> はいつになるか?・・・→<button onclick="NewDay()">計算する</button>