java 获取今天,昨天,上个月的日期
获取今天,昨天,上个月的日期 的方法:
Calendar cal = Calendar.getInstance(); //获取今天的日期 cal.setTime(new Date()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); logger.debug(year + " 年 " + month + " 月 " + day + " 日"); Date date = cal.getTime(); SimpleDateFormat format1= new SimpleDateFormat("yyyy-MM"); String dateStringYYYYMM = format1.format(date); logger.debug(dateStringYYYYMM); SimpleDateFormat format11= new SimpleDateFormat("yyyy-MM-dd"); String dateStringYYYYMMDD = format11.format(date); logger.debug(dateStringYYYYMMDD); //获取昨天的日期 cal.setTime(new Date()); //cal2.set(2018, 2, 1); cal.add(Calendar.DATE, -1); int year2 = cal.get(Calendar.YEAR); int month2 = cal.get(Calendar.MONTH)+1; int day2 = cal.get(Calendar.DAY_OF_MONTH); logger.debug(year2 + " 年 " + month2 + " 月 " + day2 + " 日"); Date date2 = cal.getTime(); SimpleDateFormat format2= new SimpleDateFormat("yyyy-MM-dd"); String dateStringYYYYMMDD2 = format2.format(date2); logger.debug(dateStringYYYYMMDD2); //获取上个月的日期(上个月的今天) cal.setTime(new Date()); cal.add(Calendar.MONTH, -1); int year3 = cal.get(Calendar.YEAR); int month3 = cal.get(Calendar.MONTH)+1; int day3 = cal.get(Calendar.DAY_OF_MONTH); logger.debug(year3 + " 年 " + month3 + " 月 " + day3 + " 日"); Date date3 = cal.getTime(); SimpleDateFormat format3= new SimpleDateFormat("yyyy-MM-dd"); String dateStringYYYYMMDD3 = format3.format(date3); logger.debug(dateStringYYYYMMDD3);