---
title: "Java中Calendar的坑"
author: "luhantu"
date: "2018-04-02T15:52:56Z"
tags: ["Calendar"]
categories: ["编程语言"]
slug: "java-calendar"
draft: false
lastmod: "2018-04-02T15:52:56Z"
id: 2415285
url: "https://luhantu.iteye.com/blog/2415285"
---

```
package com.dev.tool.log.service;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by kenny.dong on 2018/4/2.
 */
public class CalendarTest {

    /**
     * Calendar.getTime 方法是返回自1970-01-01 00:00:00 UTC（Epoch Time）的毫秒数，然后转化为Date类型。
     * 现在有一个case是：
     * 当前时间是20180329，现在有一个year=2018，month=2的年份过来，想format为yyyyMM格式
     * 如果你把年份和月份直接给到Calendar，问题就出来了
     * @throws InterruptedException
     */
    @Test
    public void calendarGetTime() throws InterruptedException, ParseException {
        int year = 2018;
        int month = 2;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(format.parse("20180331"));
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month-1);
        String DateStr = format.format(calendar.getTime());
        System.out.println(DateStr);
        /**
         * 输出结果为20180301,我们期望的输出结果应该为输出结果为20180201，怎么就整整多了一个月？
         * 这个是因为Calendar的set方法，仅仅是把月份的值给更改了。但是Calendar最终是根据毫秒数来推算
         * 它所代表的时间的，那么他的DAY天数没有变，因为201802正好没有29号，那么Calendar就等于是2月28日
         * 然后加1天，那么就是20180301了！如果当前时间是20180331，那么输出就是20180303啦！
         *所以使用Calendar，可以  calendar.set(Calendar.DAY_OF_MONTH,1);设为月初比较保险。
         */
    }

    @Test
    public void calendarGetTimeOk() throws InterruptedException, ParseException {
        int year = 2018;
        int month = 2;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(format.parse("20180331"));
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month-1);
        calendar.set(Calendar.DAY_OF_MONTH,1);//设为月初
        String DateStr = format.format(calendar.getTime());
        System.out.println(DateStr);
    }
}
```