Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Increase date by given int

Status
Not open for further replies.

bobrivers2003

Technical User
Oct 28, 2005
96
0
0
GB
Hi there,

I have the following code:

DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(new Date()));

that prints the date in a given format. In this class I have an intand based on that int I would want to increase/decrease the date by that value. E.g. if the date is 12/10/2006 and the given int was 2 I want to change the date to 14/10/2006. (Likewise for -ve numbers)

I have heard of calendar objects but have no idea how to implement them.

Any help would be greatly appreciated.

Thanks and Regards
 
This code will roll the date forward by 14 days from today :

Calendar cal = GregorianCalendar.getInstance();
cal.roll(Calendar.DAY_OF_MONTH, 14);

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Thanks for that but when I do a System.out.println(cal) I get all the date information in the world.

Is there a way to extract the Calendar.MONTH and assign it to a variable?

Thanks again
 
For anyone who will be looking at this thread I patched this together:

import java.util.*;
import java.text.*;




public class month {

public static void main(String[] args) throws Exception {


DateFormat myDate = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = GregorianCalendar.getInstance();

int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+ 1;
int day = cal.get(Calendar.DAY_OF_MONTH);

// prints current date:
System.out.println(day + "" + month + "" + year);

// add 15 days
cal.add(Calendar.DAY_OF_MONTH, 25);

year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1;
day = cal.get(Calendar.DAY_OF_MONTH);


System.out.println(day + "" + month + "" + year);


String strDate = myDate.format(cal.getTime());

System.out.println(strDate);




}

}


Thanks for the help :)


 
Code:
Calendar cal = Calendar.getInstance();

//this month
int month = cal.get(Calendar.MONTH);

//if we've got some other date in the Date instance myDate
//then ...
cal.setTime(myDate);
int myMonth = cal.get(Calendar.MONTH);
//will get it

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top