public class out_of_date { public static void main(String[] args) { //☆☆☆遍历一个格式为【2021-05-17】的日期字符串数组,计算其中已过期的日期的数量 String[] str = new String[]{"【2021-05-19】","【2021-05-16】","【2021-05-14】"}; int count = 0; //Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Shanghai")); Calendar ca = Calendar.getInstance(); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Shanghai")); for (int i = 0;i < str.length;i++){ String yearstr = str[i].substring(1,5); String monthstr = str[i].substring(6,8); String daystr = str[i].substring(9,11); int year = Integer.parseInt(yearstr); int month = Integer.parseInt(monthstr); int day = Integer.parseInt(daystr); Calendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("Asia/Shanghai")); cal1.set(year,month - 1,day); //System.out.println(ca.getTime()); System.out.println(cal1.getTime()); System.out.println(calendar.getTime()); if (cal1.before(calendar)){//before(object time) 传进去的是时间对象,而不是传时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置你想要的格式//创建一个想要的格式对象 String dateStr = df.format(cal1.getTime());//格式对象对设定的时间进行格式化 System.out.println(dateStr + "已经过期了"); count++; } } System.out.println(count); } }
java遍历一个格式为【2021-05-17】的日期字符串数组,计算其中已过期的日期的数量
最新推荐文章于 2021-10-02 10:33:19 发布