2

I'm learning the Calendar class in Java and I am unable to understand the Set(Calendar.Day OF MONTH) method.

Here it goes:

import java.util.Calendar;  
import java.util.Date


public class TestCalender
{

 public static void main(String[] args)
    {

        Calendar cal = Calendar.getInstance();
        Date date= cal.getTime();
        System.out.println(date);
        cal.set(Calendar.DAY_OF_MONTH,33);
        //cal.set(Calendar.MONTH,13);------>(1)
        Date newdate = cal.getTime();
        System.out.println(newdate);

Output:

Fri May 12 17:30:50 CDT 2017  
Fri Jun 02 17:30:50 CDT 2017

When I uncomment the statement(1) the output changes to:

Fri May 12 17:33:22 CDT 2017  
Mon Mar 05 17:33:22 CST 2018

Here is my question:

I understood the change of Month to March but I'm not able to figure out why the date has changed to 5. As per my understanding shouldn't the date be changed to April 02 2018 (when 33 days of March is being computed since March has only 31 days the count moves to the month of April).

I will be extremely grateful if someone could help in clearing this doubt.

Thanks in advance.

Regards Roopa

4

2 回答 2

4

该类Calendar使用从 0 开始到 11 月结束的月份。因此,当您将月份设置为 13 时,您指定了次年的 2 月,“2 月 33 日”(有 28 天)是 3 月 5 日。

java.util.date 类古怪且难以使用。请改用 java.time。

于 2017-05-12T23:31:24.050 回答
2
于 2017-05-13T02:14:33.143 回答