M9A
M9A

Reputation: 3276

Iterate through date ranges without using libraries - Java

Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks

String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");

Upvotes: 2

Views: 1036

Answers (2)

Jesper
Jesper

Reputation: 206796

Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.

Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.

See the API documentation of the classes mentioned above.

Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
    doSomethingWithTheCalendar(calendar);
    calendar.add(Calendar.DATE, 1);
}

Upvotes: 6

Related Questions