Reputation: 275
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?
Upvotes: 0
Views: 861
Reputation: 308743
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.
Upvotes: 1
Reputation: 332521
To create a GregorianCalendar instance:
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
References:
Upvotes: 0
Reputation: 103135
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.
Upvotes: 3