After a little research I discovered some Calendar methods that were pretty nice.

Date date = new Date();
int daysSinceSeen = - ( rand.nextInt() % 365 );
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, daysSinceSeen);

How could this code be returning a date in 2010? Do I have a bug that I can't see? The Javadoc for the add method says to use Calendar.DAY_OF_MONTH, but that also returns dates in 2010. Hm.

Recommended Answers

All 3 Replies

After a little research I discovered some Calendar methods that were pretty nice.

Date date = new Date();
int daysSinceSeen = - ( rand.nextInt() % 365 );
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, daysSinceSeen);

How could this code be returning a date in 2010? Do I have a bug that I can't see? The Javadoc for the add method says to use Calendar.DAY_OF_MONTH, but that also returns dates in 2010. Hm.

int daysSinceSeen = - ( rand.nextInt() % 365 );

daysSinceSeen could be positive or negative, so if you're adding a positive number to calendar, 2010 could happen. rand.nextInt () could return either a positive or a negative, so the modulus operator could return a positive or a negative. You have a negative sign in front, so that will reverse things, but daysSinceSeen could still be positive or negative.

Are you sure you don't want this?

int daysSinceSeen = - ( rand.nextInt(365 ));

Seems like you are using C++ type syntax rather than Java. In C++, rand () will return a non-negative number, so daysSinceSeen would end up negative. You can't assume that in Java.

public int nextInt()

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 2^32 possible int values are produced with (approximately) equal probability.

Also, no need to do calendar.setTime(time) ; the new instance of the calendar has the current time.

BTW, if you find yourself fiddling around a lot with time related methods in your application, take a look at JodaTime.

Thanks guys. And yes, I was assuming that the rand.nextInt() was returning a positive number.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.