Java日历的setMonth方法是否有错误? [英] Does the setMonth method of Java Calendar work wrong?

查看:204
本文介绍了Java日历的setMonth方法是否有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有小代码,如下所示。我预计结果应该是 7 ,但它打印 6 。如果我取消注释行 tmp.get(Calendar.MONTH),它运行OK(打印 7 )。

I have small code such as below. I expected that the result should be 7, but it printed 6. If I uncomment the line tmp.get(Calendar.MONTH), it runs OK (prints 7).

请让我知道原因。我在MacOS中使用JDK 1.7.0_25。

Please let me know the reason. I'm using JDK 1.7.0_25 in MacOS.

public static void main(String[] args) {
    Calendar tmp = Calendar.getInstance();
    tmp.set(Calendar.DAY_OF_MONTH, 4);
    tmp.set(Calendar.MONTH, Calendar.AUGUST);
    //tmp.get(Calendar.MONTH);
    tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    System.out.println(tmp.get(Calendar.MONTH));
}

屏幕截图:

注释代码: http://gyazo.com/4c099b1b2b90d72d1954b98b134e4ac3

取消注释代码: http://gyazo.com/fe368745da168646140ca9f3a60d2021

推荐答案

因为月份索引从索引0开始。在获取月份时添加+1。它是基于c的结构复制到java中。它的索引为0到11.

Because month index starts with index 0. add +1 while get month. it is c based structure copied into java. It has indexes 0 to 11.

我认为每月的日期不正确。评论并运行它正确显示( tmp.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);

And i think day of month is incorrect. comment that and run it it shows correctly.(tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);)

    tmp.set(Calendar.DAY_OF_MONTH, 4);
    tmp.set(Calendar.MONTH, Calendar.AUGUST);
    //tmp.get(Calendar.MONTH);
    //tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    System.out.println(tmp.get(Calendar.MONTH));

默认情况下,2015年为年,8月4日为 tuesday monday

By default it takes year as 2015 and August 4 is tuesday not monday

这篇关于Java日历的setMonth方法是否有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆