输入一个日期,判断这个日期是这一年的第几天
1.switch实现(利用switch穿透)
<script>
var date = +prompt("请输入一个日期(例如:20160211):");
var year = parseInt(date / 10000);//年
var month = parseInt(date / 100) % 100;//月份
var day = date % 100;//天
var days = 0;//一年中第几天
var array = [31,28,31,30,31,30,31,31,30,31,30,31];
if(month > 12 || month < 0 || day > 31 || day < 0 || isNaN(date)){
alert("日期格式输入有误!!!");
}else{
switch(month){
case 12:
days += 30;
case 11:
days += 31;
case 10:
days += 30;
case 9:
days += 31;
case 8:
days += 31;
case 7:
days += 30;
case 6:
days += 31;
case 5:
days += 30;
case 4:
days += 31;
case 3:
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days += 29;
else
days += 28;
case 2:
days += 31;
case 1:
days += day;
}
}
console.log(date + ":" + year + "年" + month + "月" + day + "日" + ",是这一年中的第:" + days + "天");
</script>
2.for+array实现
<script>
var date = +prompt("请输入一个日期(例如:20160211):");
var year = parseInt(date / 10000);
var month = parseInt(date / 100) % 100;
var day = date % 100;
var days = 0;
var array = [31,28,31,30,31,30,31,31,30,31,30,31];
if(month > 12 || month < 0 || day > 31 || day < 0 || isNaN(date)){
alert("日期格式输入有误!!!");
}else{
// for(var i = 0; i < month - 1; i++){
// days += array[i];
// }
// if(month > 2)
// if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
// days += 1;
// days += day;
}
console.log(date + ":" + year + "年" + month + "月" + day + "日" + ",是这一年中的第:" + days + "天");
</script>