How to add days to a date in Java

To add years, days, hours or minutes to a Date object in Java, you need to use the java.util.Calendar class.

//Adds one day to the current date
Calendar cal = Calendar.getInstance(); // The current date
cal.add(Calendar.DAY_OF_MONTH, 1);
Date date = cal.getTime(); // 1 day in the future

If you want to substract time, simply use a negative number.

//Five hours ago
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -5);
Date date = cal.getTime();

There’s nothing more to it; it’s that simple!

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax