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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add a month to a date

Status
Not open for further replies.

bunnyweb

MIS
Jan 13, 2003
42
IE
Hello.

I'm trying to do something quite simple. I have a date that I want to add a month to.

So for 21/9/2004, add 1 month to get 21/10/2004.

My concern is with the year changing. So for 16/12/2004 I want to get 16/1/2005, not 16/13/2004.

I'm sure that there is some class available that does this, my guess is somewhere in java.util.calendar, but I can't quite get it.

One last thing, I need this to work for UK date formats (dd/mm/yyyy).

I don't do much Java programming, so it's all a bit fuzzy. Any help would be greatly appreciated. Thanks!
 
Take a look at this code, it demontrates how to roll a month forward :

Code:
		long now = System.currentTimeMillis();
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(now);
		
		Date before = new Date(gc.getTimeInMillis());
		System.err.println(before);
		
		gc.roll(Calendar.MONTH, 1);
		
		Date after = new Date(gc.getTimeInMillis());
		System.err.println(after);

You can parse and format Stings into Date objects using the java.text.SimpleDateFormat class :



--------------------------------------------------
Free Database Connection Pooling Software
 
Here's the streamlined version of the code above. Taking out the unnecessary steps, and adding the steps to parse string dates in UK format.
Code:
String dateString = "21/9/2004";
SimpleDateFormat dateFormat = new SimpleDateFormat("d/m/yyyy");
Date before = dateFormat.parse(dateString, 0);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(before);

gc.roll(Calendar.MONTH, 1);
Date after = gc.getTime();
dateString = dateFormat.format(after);

That takes it from string format, rolls the month field and puts it back in string format.

 
Sorry:
javadocs:
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
which indicates, that the year will not change, but stay the same - therefore roll.

My first intention was: hey - dates are allways complicated, copy that snipplet, for later use, you don't know when you will need it!
My test struggled on the larger field issue.
Well - let's read the javadoc:
add(int field, int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.

So replace roll with add - and you're done.
I thought.
No success.

Here is my cut'n'paste class.
Code:
import java.util.*;
import java.util.Calendar.*;
import java.text.*;
/**
	DateManipul

	@date Do Aug  5 03:21:07 CEST 2004
*/
public class DateManipul
{
	/** */
	public DateManipul (String sDate, String format, char unit, int value)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat (format);
		Date date = null;
		try
		{
			date = dateFormat.parse (sDate);
		}
		catch (ParseException pe)
		{
			pe.printStackTrace ();
			System.exit (4);
		}

		GregorianCalendar gc = new GregorianCalendar ();
		gc.setTime (date);
		int iUnit = 0;
		switch (unit)
		{
			case 'm': iUnit = Calendar.MONTH; break;
			case 'd': iUnit = Calendar.DAY_OF_YEAR; break;
			case 'y': iUnit = Calendar.YEAR; break;
			case 'w': iUnit = Calendar.WEEK_OF_YEAR; break;
			default: usage ("Sorry, unsupported unit, valid: [dwmy]. Found " + unit);
				System.exit (3);
		}
		gc.add (iUnit, value);
		date = gc.getTime();
		System.out.println (dateFormat.format (date) + "\t\t" + iUnit);
	}

	/** */
	public static void main (String args[])
	{
		String date = null;
		String format = null;
		char unit = '\0';
		int value = 0;
		if (args.length != 4)
		{
			usage ("Sorry, 4 arguments expected. Found: " + args.length);
			System.exit (1);
		}
		date = args[0];
		format = args[1];
		unit = (args[2]).charAt (0);
		try
		{
			value = Integer.parseInt (args[3]);
		}
		catch (NumberFormatException nfe)
		{
			usage ("Sorry, value needs to be an int. Found: " + args[4]);
			System.exit (2);
		}
		new DateManipul (date, format, unit, value);
	}

	/** */
	public static void usage (String message)
	{
		if (message != null)
			System.out.println (message);
		System.out.println ("Usage:\tjava DateManipul date, format, unit, value");
		System.out.println ("\tdate:\t19-03-04 (according to format)");
		System.out.println ("\tformat:\td-m-yy");
		System.out.println ("\tunit:\tm [dwmy]");
		System.out.println ("\tvalue:\t-3");
		System.out.println ("\tExample:\tsubstract 3 months from 19-03-04 => 19-12-03");
	}
}
Where are we wrong?

I tested with DAY_OF_MONTH too, instead of DAY_OF_YEAR.
For adding values, the Concept is - well - misguided.
When I add a day to a specific date, I add a day, - not a DAY_IN_MONTH or DAY_IN_YEAR.

It's a time-period.
How can you add a DAY_IN_YEAR to a date? Isn't that nonsense?

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top