java - Simpledateformat - 为什么 Calendar.MONTH 错误地生成 16 年 1 月的上个月值(即 Dec-2015)?

标签 java calendar simpledateformat

我一直在尝试使用 Simpledateformat 从当前月份获取过去 12 个月的值。但是对于上个月(即 2015 年 12 月),我总是得到 2016 年 12 月。

calendar.set(Calendar.MONTH, -1); 这应该会在 2015 年 12 月返回,但实际上并没有。

我不明白这个逻辑。有人可以解释一下吗?非常感谢您的时间和帮助。

我的代码:

public static void main (String[] args) throws java.lang.Exception
{
    SimpleDateFormat month_date = new SimpleDateFormat("MMM-YYYY");

    Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, -1);


        String month_name = month_date.format(calendar.getTime());
        System.out.println("month_name : "+month_name);

}

输出:

month_name : Dec-2016

最佳答案

要减去月份,您可以这样做:

calendar.add(Calendar.MONTH, -1);

希望对你有帮助。

关于java - Simpledateformat - 为什么 Calendar.MONTH 错误地生成 16 年 1 月的上个月值(即 Dec-2015)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35083824/

相关文章:

events - 使用 Microsoft graph 创建事件时出错

java - 关于java日历逻辑的帮助

java - 处理后获得的日期不正确

java - 在 Java 中将字符串转换为日历对象

java - 局部变量隐藏一个字段是什么意思?

java - 设置 Iterable 的所有对象的属性

ios - swift 中的协议(protocol)引用抛出段错误 11

java - 更改日期格式

java - 如何在 Java 中声明类类型数组

java - 使用合作伙伴 WSDL 连接到 SFDC 的测试实例