views:

138

answers:

3

I am doing an assignment and it involves using the GregorianCalendar. The specs say I need to use setLenient(false); how do I do this? I also need to set a constant date (1/1/2009) so that the first day of my program is always that.

It also says to access the day, month and year through this:

get(1) //returns the year
get(2) // returns the month
get(5) /// returns the day

To add n days to the date, call the add method with a field number of 5: add(5, n);

To subtract: add(5, -n);

Can someone please explain what that means and how to implement it?

A: 

Create an instance of Calendar and call setLenient on it.

Calendar cal = Calendar.getInstance();
cal.setLenient(false);

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

UPDATE:

And since you only mentioned SimpleDateFormat in your comment, here's an example for it as well:

Date today = cal.getTime();
DateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd");
System.out.println(formatter.format(today));

Java Almanac is a good source for simple code snippet examples like these.

duffymo
I need to use gregorian calendar though, isnt that using simpledateformat?
Karen
If the default calendar for your timezone is Gregorian, you ARE using it.
duffymo
+3  A: 

Start by visiting the API docs here. These docs explain exactly what methods are available in a class in Java.

To get a Calendar for instance you can:

  Calendar c = Calendar.getInstance();

You will see in the docs that there are actually a number of ways to get a Calendar and the default is a GregorianCalendar.

Once you have the Calendar object then you can call any method passing the necessary parameters. For example,

 c.setLenient(true);

To use the get methods you have to specify the field that you wish to get.

int month  = c.get(Calendar.MONTH);

and so on.

Vincent Ramdhanie
A: 

To create a GregorianCalendar instance:

Calendar cal = new GregorianCalendar();
cal.setLenient(false);

References:

OMG Ponies