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.
long theFuture = System. currentTimeMillis() + (86400 * 7 * 1000); Date nextWeek = new Date(theFuture);
get(Calendar. DAY_OF_MONTH) + 1; will it display tomorrow's date. or just add one to today's date? For example, if today is January 31.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
The two methods will behave differently on daylight savings boundaries. The first method will continue returning the same time of the day, regardless of daylight savings status. The second method will return times which vary an hour in each direction as daylight savings time starts and stops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With