赞
踩
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.util.Scanner;
-
- public class Text {
- public static void main(String[] args){
- while (true) {
- //System.out.println(localDate());加入了判断闰月
- System.out.println(localDate1());//没有加判断 是否是闰月,所以存在不是闰年,但2月有29号
- }
- }
-
- //判断输入的日期格式是否正确,加入了判断是否是闰月
- //因为加入了判断是否是闰月,所以日期的输入必须是正确的
- //月份0开头分为【1,3,5,7,8】31天(0[1-9] , [12][0-9] , 3[01])与【4,6,9】30天(0[1-9] , [12][0-9] , 30);
- //月份1开头分为【0,2】31天(0[1-9] , [12][0-9] , 3[01])与【1】30天(0[1-9] , [12][0-9] , 30);
- //例外2月份同上,闰月29天,正常28天;
- public static boolean localDate(){
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入时间:(yyyy-MM-dd)");
- String localDate = sc.next();//获取输入日期
- DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");//格式化时间
- LocalDate localDate1 = LocalDate.parse(localDate , dateTimeFormatter);//解析时间
- int year = localDate1.getYear();//获取年份
- //判断是否为闰年
- if((year % 4 == 0 && year % 100 !=0) || year % 400 == 0) {//输入的年份是闰年
- if (localDate.matches("\\d{4}-(((0[13578]-((0[1-9])|([12][0-9])|(3[01])))|(0[469]-((0[1-9])|([12][0-9])|(30))))" +
- "|((1[02]-((0[1-9])|([12][0-9])|(3[01])))|(11-((0[1-9])|([12][0-9])|(30))))" +
- "|(02-((0[1-9])|(1[0-9])|(2[0-9]))))")){//闰年2月有29天
- return true;
- }
- }else{//输入的不是闰年,2月就28天
- if(localDate.matches("\\d{4}-(((0[13578]-((0[1-9])|([12][0-9])|(3[01])))|(0[469]-((0[1-9])|([12][0-9])|(30))))" +
- "|((1[02]-((0[1-9])|([12][0-9])|(3[01])))|(11-((0[1-9])|([12][0-9])|(30))))" +
- "|(02-((0[1-9])|(1[0-9])|(2[0-8]))))")){
- return true;
- }
- }
- return false;
- }
-
- //直接判断,没有加是否是闰月
- public static boolean localDate1(){
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入时间:(yyyy-MM-dd)");
- String localDate = sc.next();//获取输入日期
- if (localDate.matches("\\d{4}-(((0[13578]-((0[1-9])|([12][0-9])|(3[01])))|(0[469]-((0[1-9])|([12][0-9])|(30))))" +
- "|((1[02]-((0[1-9])|([12][0-9])|(3[01])))|(11-((0[1-9])|([12][0-9])|(30))))" +
- "|(02-((0[1-9])|(1[0-9])|(2[0-9]))))")){
- return true;
- }
- return false;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。