日期的部分操作
日常笔记记录
public class DateUtil {
public static Date getDate(Date date){
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Calendar nowTime=Calendar.getInstance();//获取当前日期
nowTime.setTime(date);
nowTime.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
nowTime.set(Calendar.HOUR_OF_DAY, 0);//将小时至零
nowTime.set(Calendar.MINUTE, 0);//将分钟至零
nowTime.set(Calendar.SECOND, 0);//将秒至零
nowTime.set(Calendar.MILLISECOND, 0);//将毫秒至零
return nowTime.getTime();
}
public static int getMonth(String lastMonth,String thisMonth){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int result = 0;
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(thisMonth));
int year1 = c.get(Calendar.YEAR);
int month1 = c.get(Calendar.MONTH);
c.setTime(sdf.parse(lastMonth));
int year2 = c.get(Calendar.YEAR);
int month2 = c.get(Calendar.MONTH);
if(year1 == year2) {
result = month1 - month2;
} else {
result = 12*(year1 - year2) + month1 - month2;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
int month = getMonth("2020-01", "2020-01");
System.out.println(month);
}
}