Adding || subtracting dates in java

I see so many posts around so many forums where people want help on adding or subtracting days from a specific date. So I thought Id leave on the wild world of the net some help which might come handy to someone, someday. Here it is.. you can either follow the logic and add some jazz to it and become the hero of your project or do what most of us happily do, copy paste !

import java.util.Calendar;
import java.util.Date;
public class DateAdder {
public Date addOrSubstractDaysFromDate(Date aDate,int noOfDays) {
Calendar calendar = Calendar.getInstance(); //get teh calendar instance
calendar.setTime(aDate);//set it to today
calendar.add(Calendar.DATE, noOfDays);// this is where the adding || subtracting happens
return calendar.getTime();

public static void main(String[] args){
Date today = new Date();
DateAdder dateAdd = new DateAdder();
System.out.println(“Date today : “+today);
System.out.println(“Date after 10 days : “+ dateAdd.addOrSubstractDaysFromDate(today, 10));
System.out.println(“Date before 10 days : “+dateAdd.addOrSubstractDaysFromDate(today, -10));

enjoy madi

P.S: the formatting is as usual screwy, or may be I dont know how to do it. This is the best I can do to help. If you need further assistance leave a message and Ill see what I can do for ya !!



4 Responses to “Adding || subtracting dates in java”

  1. chandan Says:

    thanks maga

  2. noryahya Says:

    but how if i wanna subtracting today with an another day..
    like 2009-10-10 – 2009-9-12

    can you give me some clue..

  3. noryahya Says:

    thx if you show the code

  4. Ye Ye Ni Says:

    thanks a lot.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: