import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class Test { public static List<String> findDates(String stime, String etime) throws ParseException { List<String> allDate = new ArrayList(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date dBegin = sdf.parse(stime); Date dEnd = sdf.parse(etime); allDate.add(sdf.format(dBegin)); Calendar calBegin = Calendar.getInstance(); // 使用给定的 Date 设置此 Calendar 的时间 calBegin.setTime (dBegin); Calendar calend Calendar.getInstance = (); // set the given time this Calendar Date calEnd.setTime (DEND); // test if this date is after the specified date while (dEnd.after (calBegin.getTime ())) { // a calendar rules, adding or subtracting a specified amount of time for a given calendar field calBegin.add (Calendar.DAY_OF_MONTH,. 1); allDate.add (sdf.format (calBegin .getTime ())); } return allDate; } public static void main (String [] args) { // test data String stime = "2019-05-01"; String etime = "2019-05-05"; / / collection contains 2019-05-01 / 2019-05-05, need not be removed List <String> = new new List the ArrayList <> (); the try { = New new SDF the SimpleDateFormat the SimpleDateFormat ( "the MM-dd-YYYY"); Long Long.valueOf S = (sdf.parse (stime) .getTime ()); Long E = Long.valueOf (sdf.parse (etime) .getTime ( )); // only when the end time is larger than the start time query IF (S <E) { List = findDates (stime, etime); } } the catch (a ParseException E) { e.printStackTrace (); } for (String time : List) { System.out.println (Time); } System.out.println "number of days:" (+ list.size ()); } }
Original: https: //blog.csdn.net/qq_38955717/article/details/90448848