Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generate all dates between x and y [duplicate]

I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?

private ArrayList<Date> GetDateRange(Date start, Date end) {
    if(start.before(end)) {
        return null;
    }

    int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
    ArrayList<Date> listTemp = new ArrayList<Date>();
    Date tmpDate = start;

    do {
        listTemp.add(tmpDate);
        tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
    } while (tmpDate.before(end) || tmpDate.equals(end));

    return listTemp;
}

To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know. Thanks

like image 703
sys_debug Avatar asked Nov 27 '22 07:11

sys_debug


1 Answers

Joda-Time

Calendar and Date APIs in java are really weird... I strongly suggest to consider jodatime, which is the de-facto library to handle dates. It is really powerful, as you can see from the quickstart: http://joda-time.sourceforge.net/quickstart.html.

This code solves the problem by using Joda-Time:

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;


public class DateQuestion {

    public static List<DateTime> getDateRange(DateTime start, DateTime end) {

        List<DateTime> ret = new ArrayList<DateTime>();
        DateTime tmp = start;
        while(tmp.isBefore(end) || tmp.equals(end)) {
            ret.add(tmp);
            tmp = tmp.plusDays(1);
        }
        return ret;
    }

    public static void main(String[] args) {

        DateTime start = DateTime.parse("2012-1-1");
        System.out.println("Start: " + start);

        DateTime end = DateTime.parse("2012-12-31");
        System.out.println("End: " + end);

        List<DateTime> between = getDateRange(start, end);
        for (DateTime d : between) {
            System.out.println(" " + d);
        }
    }
}
like image 61
Matteo Avatar answered Dec 04 '22 22:12

Matteo