Java – iterate between two dates, including the start date?
•
Java
Sorry for asking repeated questions
public static void main(String[] args)throws Exception { GregorianCalendar gcal = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM"); Date start = sdf.parse("2010.01"); Date end = sdf.parse("2010.04"); gcal.setTime(start); while (gcal.getTime().before(end)) { gcal.add(Calendar.MONTH,1); Date d = gcal.getTime(); System.out.println(d); } }
Between the above code print date, but I need to print the start date also
The code output above is
Mon Feb 01 00:00:00 IST 2010 Mon Mar 01 00:00:00 IST 2010 Thu Apr 01 00:00:00 IST 2010
But I also need to start dating on the output
Please help me solve this problem and thank you in advance
Solution
In my opinion, this is the best way:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM"); Date start = sdf.parse("2010.01"); Date end = sdf.parse("2010.04"); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTime(start); while (!gcal.getTime().after(end)) { Date d = gcal.getTime(); System.out.println(d); gcal.add(Calendar.MONTH,1); }
Output:
Fri Jan 01 00:00:00 WST 2010 Mon Feb 01 00:00:00 WST 2010 Mon Mar 01 00:00:00 WST 2010 Thu Apr 01 00:00:00 WST 2010
All we do is print the date before increment, and then repeat if the date is not after the end date
Another option is to copy the print code before while (yuck) or use do... While (also yuck)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码