Adding months to Date

L

Larry Coon

I understand the differnece between Date and Calendar, and why
I would prefer to use Calendar. However, I'm stuck with Date
in this instance.

I want to add a secific number of months to a Date. Looks like
I do it by converting to a Calendar, using Calendar.add(), and
converting back to Date. The following SSCCE isn't working for
me -- endDate is unchanged from beginDate. Can anyone point out
what I'm doing wrong (or if there's a better approach)? Thanks.

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

public class Test {
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("mm/dd/yyyy");
Date beginDate = format.parse("10/01/2005", new ParsePosition(0));

GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(beginDate);
calendar.add(Calendar.MONTH, 3);
Date endDate = calendar.getTime();

System.out.println("Begin: " + format.format(beginDate));
System.out.println("End: " + format.format(endDate));
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Date/Calendar confusion 8
Date/Calendar confusion 0
java date issues 2
Date different 32
Date wierdness 1
Date constructor for long. 3
How to convert String to Date 0
java.sql.Date returning wrong date 7

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top