I am reviewing some code at work and came across an inconsistency in how the code handles adding 1 week to the current time and was wondering if there was any reason why one should really be preferred over the other:
The first was a utility method:
public static Date addDaysToDate(final Date date, int noOfDays) {
Date newDate = new Date(date.getTime());
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.add(Calendar.DATE, noOfDays);
newDate.setTime(calendar.getTime().getTime());
return newDate;
}
And the second used simple millisecond arithmetic:
long theFuture = System.currentTimeMillis() + (86400 * 7 * 1000);
Date nextWeek = new Date(theFuture);
The second method obviously uses 'magic numbers' to define a week, but this could be moved to a constant MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000
So other than that, is there any reasons why one of these methods should be preferred over the other?
Basically I want to change the code to be consistent throughout, but I'm not entirely sure which one to remove. So any arguments one way or the other would be useful.
DateTime newDate = date.plusWeeks(1);
– VelutinousGregorianCalendar
, and bothDate
classes bundled with Java were years ago supplanted by the modern java.time classes defined in JSR 310, and built into Java 8+. – Anastasia