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 method is to return the milliseconds since 1970-01-01 00:00:00 UTC (Epoch Time), and then convert it to Date type. * Now a case is: * The current time is 20180329, and now there is a year with year=2018, month=2, and I want the format to be yyyyMM format * If you give the year and month directly to Calendar, the problem comes out * @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); /** * The output result is 20180301. The output result we expect should be 20180201. Why is there an extra month? * This is because the set method of Calendar only changes the value of the month. But Calendar is ultimately calculated based on milliseconds * The time it represents, then his DAY days have not changed, because 201802 just doesn't have the 29th, then Calendar is equal to February 28th * Then add 1 day, then it is 20180301! If the current time is 20180331, then the output is 20180303! *So to use Calendar, you can set calendar.set(Calendar.DAY_OF_MONTH, 1); to be safer at the beginning of the month. */ } @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);//Set as the beginning of the month String DateStr = format.format(calendar.getTime()); System.out.println(DateStr); } }