1、输入月份,显示当月的天数, 利用case穿透简化代码
var month = prompt("请输入月份"); var year = prompt("请输入年份"); // month是字符串类型 需要类型转换 switch(Number(month)){ case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 : alert("31天"); bresk; case 4 : case 6 : case 9 : case 11 : alert("30天"); bresk; case 2 : //判断平年闰年 if(year % 4 ===0 && year % 100 !==0 || year % 400 ===0){ alert("29天"); }else{ alert("28天"); } }
2、根据日期,判断这个日期是这一年的第几天。例如: 2016,02,11,计算后结果为42
1 <script> 2 var date_string = prompt("请输入八位数日期"); 3 // 拆分日 4 var date = date_string % 100; 5 // 拆分月 6 var months = parseInt(date_string / 100) % 100; 7 // 拆分年份 8 var years = parseInt(date_string / 10000); 9 // console.log(years,months,date); 10 // 根据年月日判定当前日期已经经过了多少天 11 var days = 0; 12 switch(months - 1){ 13 case 11 : 14 days += 30; 15 case 10 : 16 days += 31; 17 case 9 : 18 days += 30; 19 case 8 : 20 days += 31; 21 case 7 : 22 days += 31; 23 case 6 : 24 days += 30; 25 case 5 : 26 days += 31; 27 case 4 : 28 days += 30; 29 case 3 : 30 days += 31; 31 case 2 : 32 // 判断平年闰年 33 if(years % 4 === 0 && years % 100 !==0 || years % 400 === 0){ 34 days += 29; 35 }else{ 36 days += 28; 37 } 38 case 1 : 39 days += 31; 40 } 41 // 加上当月的日期 42 days += date; 43 console.log(days); 44 </script>