Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 1 Week to a Date, which way is preferred?

Tags:

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.

like image 370
DaveJohnston Avatar asked Jul 21 '10 14:07

DaveJohnston


People also ask

How to add 1 Week from current date in Java?

long theFuture = System. currentTimeMillis() + (86400 * 7 * 1000); Date nextWeek = new Date(theFuture);

How can I get tomorrow date in dd mm yyyy format in Java?

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.

How can I compare two dates in Java?

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.


1 Answers

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.

like image 164
Erick Robertson Avatar answered Oct 05 '22 23:10

Erick Robertson