package org.example; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; public class test2 { public static void main(String[] args) { String date="2019-07-13"; //给定日期 String regex="(\\d{4})-(\\d{1,2})-(\\d{2})"; //正则匹配规定日期格式 if (date.matches(regex)){ //当匹配成功时 Matcher matcher = Pattern.compile(regex).matcher(date); matcher.find(); //这里为空跑,只会返回一个布尔值 int year = Integer.parseInt(matcher.group(1)); //提取年月日 int month = Integer.parseInt(matcher.group(2)); int day = Integer.parseInt(matcher.group(3)); int total = day; for (int i=1;i<month;i++){ //开始匹配大小月 int d=31; //默认为大月31天 switch (i){ case 4:case 6:case 9:case 11: //小月时天数为30天 d=30; break; case 2: //二月特殊,计算出是否为闰年来判断二月有几天 d = year%4==0 && year%100!=0 || year%400==0 ? 29:28; break; } total+=d; //算出总天数 } System.out.println(MessageFormat.format("{0}是{1}的第{2}天",date,year,total)); //对应输出 }else{ System.out.println("非法日期"); //当格式不符合时返回值 } } }
如有不足,欢迎指正。