Java Timestamp - Adding five minutes

You should use Calendar class to manipulate Date and time:

The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week

  Date dNow = new Date( ); // Instantiate a Date object
  Calendar cal = Calendar.getInstance();
  cal.setTime(dNow);
  cal.add(Calendar.MINUTE, 5);
  dNow = cal.getTime();

Ignoring Dates and focusing on the question.

My preference is to use java.util.concurrent.TimeUnit since it adds clarity to my code.

In Java,

long now = System.currentTimeMillis();

5 minutes from now using TimeUtil is:

long nowPlus5Minutes = now + TimeUnit.MINUTES.toMillis(5);

Reference: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html


Instead of starting with

new Date()

start with

new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5))

This will give you a Date instance that represents your required point in time. You don't need to change any other part of your code.

Tags:

Java