Question

I am trying to add a random number of days to the date January 1, 2010 to make the new date fall between then and today (December 2, 2013). The total number of days between the two dates is 1431. I Googled how to do this, and found to add hours, you need only use HOUR field. However, when I try to use the DATE field, I get years way out of the expected range.

import java.util.Random;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateArithmetic{
    public static void main(String[] args){
            Random random = new Random();
            Calendar gc = new GregorianCalendar(2010, Calendar.JANUARY, 1, 0, 0, 1);

            System.out.println(gc.getTime());

            for(int i=0; i<100; i++){
                    gc.add(GregorianCalendar.DATE, random.nextInt(1431));
                    System.out.println(gc.getTime());
            }
    }
}
Was it helpful?

Solution

You are adding a random number of days 100 times to the same Calendar object. It makes sense that it would almost immediately advance well past today into the future.

Re-initialize your GregorianCalendar object on each loop to the initial date.

OTHER TIPS

I can suggest you do this

        -->Date date = gc.getTime();
        for(int i=0; i<100; i++){
            int val = random.nextInt(1431);
            gc.set(Calendar.DAY_OF_YEAR, val);
            System.out.println(gc.getTime() + " VAL=" + val);
            -->gc.setTime(date);
        }

Save your first date and set it back every loop.

I would suggest using JodaTime to achieve that. The java date api is old and bugy.

JodaTime: http://www.joda.org/joda-time/

In joda time it would look something like this in locale timezone:

final DateTime dateTime = new DateTime("01-01-2010");
dateTime.plusDays(random.nextInt(1431));

or even better:

final DateTime dateTime = new DateTime("01-01-2010");
final Duration duration = new Duration(dateTime, DateTime.now());
dateTime.plusDays(random.nextInt((int)duration.getStandardDays()));

All the above solutions are correct.But i just modify your code that is every time reinitialize your gc object

import java.util.Random;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class DateArithmetic{
public static void main(String[] args){
        Random random = new Random();
        Calendar gc = new GregorianCalendar(2010, Calendar.JANUARY, 1, 0, 0, 1);

        System.out.println(gc.getTime());

        for(int i=0; i<100; i++){
                gc.add(GregorianCalendar.DATE, random.nextInt(1431));
                System.out.println(gc.getTime());
                gc = new GregorianCalendar(2010, Calendar.JANUARY, 1, 0, 0, 1);
        }
    }
}

This is also work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top