Skip to content Skip to sidebar Skip to footer

How To Iterate Over A Date Range In The Following Format 25-12-2012 To 31-12-2012(hyphen Should Be Maintained) In Java?

I want to handle the leap years Feb 29 cases as well. I tried the following, but having trouble in converting each time format to dd-mm-yyyy. GregorianCalendar gcal = new Gregoria

Solution 1:

java.util.Date is the wrong type for this. It has millisecond (not day) precision. java.time.LocalDate is more appropriate. Use ThreeTen if you need Java <8 compatibility.

To format a LocalDate:

localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))

Solution 2:

A Date object is simply a container for the number of milliseconds since the Unix epoch, the format is irrlevent.

The Date's toString method simply uses the system local to provide a human readable representation of it's content. You can not modify this format (directly and nor should you, because it will change on the next machine you run your code on)

If you want to display the Date in a given format then you should use an appropriate formatter, for example...

System.out.println( sdfd.format(gcal.getTime()));

Solution 3:

Date-Only

The answer by Chris Martin is correct. If you are not comparing the beginning/ending of days across time zones, then you can use a class for date-only without any time-of-day or time zone component.

Joda-Time & java.time

In addition to the java.time package, you can use Joda-Time which inspired java.time. Both java.time and Joda-Time offer a LocalDate class. Both frameworks have their strengths and weaknesses. You can use both frameworks in a project if you are careful with your import statements.

Example Code

Example code in Joda-Time 2.3.

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );

// LocalDate start = formatter.parseLocalDate( "26-02-1989" );
LocalDate start = new LocalDate( 1989, 2, 26 );
LocalDate stop = new LocalDate( 1989, 3, 6 );
LocalDate localDate = start;
while ( localDate.isBefore( stop ) )
{
    String output = formatter.print( localDate );
    localDate = localDate.plusDays( 1 );
}

Post a Comment for "How To Iterate Over A Date Range In The Following Format 25-12-2012 To 31-12-2012(hyphen Should Be Maintained) In Java?"