与以往使用switch结构判断月份与闰年不同,我直接使用if语句与数组截取的方法判断年份和计算天数
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String str=request.getParameter("time"); //从输入页接收的日期变量
boolean r=str.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}");
if(r){
String[]strings=str.split("-"); //使用split方法截取字符串,区分年月日
int year = Integer.parseInt(strings[0]);
int month = Integer.parseInt(strings[1]);
int day = Integer.parseInt(strings[2]);
int count=0,count1=0;
for(int i=1;i<month;i++){
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
count++;
}else{
count1++;
}
}
if(year>0&&month>0&&month<13&&day>0&&day<=31){
if(month!=2){
if ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
int days=count*31+count1*30-1+day;
session.setAttribute("days", days); //使用session保存days
response.sendRedirect("result5.jsp"); //跳转到结果页面
}else{
int days=count*31+count1*30-2+day;
session.setAttribute("days", days);
response.sendRedirect("result5.jsp");
}
}else{
int days=count*31+count1*30+day;
session.setAttribute("days", days);
response.sendRedirect("result5.jsp");
}
}
} else{
response.sendRedirect("input5.jsp");
}
%>
</body>
</html>
这是我们jsp老师布置的练习题,希望能帮助到你。
(CCUT YYDS)