有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

日期为什么日历类(Java)要重置其字段?

我正在尝试设置日历类实例的属性。但每次我到12月30日,它就会重新设置到下一年。这是日历课上的抽签吗

public Calendar setCalendar()
{
    String Date = "2013-12-30";
    int yyyy = Integer.parseInt(date.substring(0,4));
    int mm = Integer.parseInt(date.substring(5,7));
    int dd = Integer.parseInt(date.substring(8,10));
    System.out.println(yyyy + " " + mm + " " + dd);
    Calendar Cal= new GregorianCalendar();
    Cal.set(yyyy,mm,dd);
    System.out.println(Cal.get(Calendar.YEAR)+","+Cal.get(Calendar.MONTH));

    return Cal;
}

输出: 2013 12 30 2014,0


共 (2) 个答案

  1. # 1 楼答案

    检查日历API文档,月值基于0,即一月为0

    month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

    您正在将月份设置为12。这实际上给了你下一年的时间。要纠正错误,请尝试:

    Cal.set(yyyy,mm-1,dd);
    

    希望有帮助

  2. # 2 楼答案

    使用Calendar时,月份是以0为基础的,因此您实际上将月份设置为明年的一月

    如果您真的需要使用Calendar,我建议至少使用SimpleDateFormatString解析为Date,并使用它设置日历