简体   繁体   中英

How to iterate over range of date in java

     SimpleDateFormat dateformat2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    Date date = new Date();
    String d=dateformat2.format(date);

Now I want to iterate from current date to next 3 month date.I want to date format need to same. Any suggestion?

I'm not entirely sure what you mean in your question, but I'm guessing it has to do with iterating over dates for 3 months. If that is the case, you can try something like this:

for(int i = 0; i < month; i++) {
    for(int j = 0; j < day; j++) {
        //do something...
}}

Just set month to be the amount of months to iterate over (in this case 3), and day to be the number of days per month.

If the months in question don't necessarily have a consistent amount of days each, then you can try something a little different like this:

First set a variable to the days total to iterate. You can get at this by calculating from a set definition of days in each respective month. Then just iterate over the days

for(int i = 0; i < daysLeftToIterate; i++) {
    //do something...
}

Edit:

After looking into Calendar, I think there may be a way to use that efficiently to solve your issue. You can define a Calendar object in "lenient mode" as described on the API:

"Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1."

By doing that, you can define to search over a set amount of days, instead of months. For example, you can define the entire period of time as Month=January, Day=90, which would give the date of the 90th day in the year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM