简体   繁体   中英

GregorianCalendar

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?

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.

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.

To create a GregorianCalendar instance:

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

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM