I'm making a video game in Java and I ran into a problem where I need date to be managed accurately. The game will start off somewhere in 2010 and it needs to continue on day after day following the Gregorian calendar. I won't be using hours or minutes whatsoever so the only important thing to me is that after telling my program to go one day into the future, it needs to correctly know that February has only 28 days and that December has 31 days, etc.
I know there is a Java Date class but I did NOT see any kind of 'go X dates' method in the API (the reason that's not there is beyond me). There is a set date feature but that won't work for me as my program won't be sure which months have less/more days, etc.
Thanks for the help!
You should either use Joda Time if you're still using Java 7 or earlier (in which case you should also be looking to move to Java 8), or the java.time
package if you're using Java 8.
In both cases, you want the LocalDate
class, which is used to represent a date without a time, and without any associated time zone.
It's a much, much cleaner API to use than the antiquated and horrible java.util.Calendar
(or java.util.Date
). No bizarre constants to worry about instead of simple method calls, no 0-based months etc.
You can just use:
date = date.plusDays(1);
to advance the date. Great!
See more on this question at Stackoverflow