简体   繁体   中英

How to use calendar to create date

i need to use Calendar to create date at which i specify the month , the week number and the day of week. i am creating new instance of calendar: **

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK,7);
c.set(Calendar.WEEK_OF_MONTH,1);
c.set(Calendar.MONTH,10);

** when calling c.getTime(); instead of getting the first Saturday of November i am getting the last Saturday of october?

You need to correct Calendar constants values. Please refer to below code it works fine. Please remember Month value in calendar starts with 0 and 1 ie, month as 0 means month as Jan .

Calendar c = Calendar.getInstance();
    c.set(Calendar.DAY_OF_WEEK,4);
    c.set(Calendar.WEEK_OF_MONTH,4);
    c.set(Calendar.MONTH,7);

The DAY_OF_WEEK is Sunday through Saturday. The value 7, indicates SATURDAY . The WEEK_OF_MONTH is

Field number for get and set indicating the week number within the current month. The first week of the month, as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek(), has value 1. Subclasses define the value of WEEK_OF_MONTH for days before the first week of the month.

The MONTH numbers start at 0, so 10 is November. You haven't specified a year, so it uses the current year.

November's first week Saturday falls on

Sat Nov 02 11:19:24 EDT 2013

What else are you expecting? October? Change your MONTH value to 9 .

Try this

  c.set(2000, 7, 4);  // YYYY M D

  // print the result
  System.out.println("Altered date is :" + cal.getTime());

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