Date date = new Date();//当前时间
String data1 = "2022-01-01";//指定专门的时间
String format = "yyyy-MM-dd HH:mm:SS";
SimpleDateFormat sd = new SimpleDateFormat(format);
Date parse = null;
try {
parse = sd.parse(new Data());//将指定的时间进行转换成Date类型
} catch (java.text.ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(parse);
c.add(Calendar.MONTH, -1);//减去当前日期的一个月
c.add(Calendar.YEAR,-1);//减去当前日期的一年
String format1 = sd.format(c.getTime());
System.out.println(format1);
获取指定月份之间相差月份数量
String oldDateStr="202201";//指定一个日期------------
SimpleDateFormat sdf =new SimpleDateFormat( "yyyyMM");
Date oldDate= null;
try {
oldDate = sdf.parse(oldDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar= Calendar.getInstance();//获取日历对象
calendar.clear();
calendar.setTime(oldDate);
int oldYear =calendar.get(Calendar.YEAR);//获取指定日期年份
int oldMonth =calendar.get(Calendar.MONTH)+1;//获取指定日期的月份
String currentDate="202205";//指定另一个日期------------
Date currentDate1= null;
try {
currentDate1= sdf.parse(currentDate);
} catch (ParseException e) {
e.printStackTrace();
}
calendar.clear();
calendar.setTime(currentDate1);
int currentYear=calendar.get(Calendar.YEAR);//当前日期的年份
int currentMonth =calendar.get(Calendar.MONTH)+1;//当前日期的月份
String curDate=sdf.format(currentDate1);
//currentMonth可能会比oldMonth小,因此要加绝对值
int betweenMonth =Math.abs((currentYear-oldYear)* 12 +(currentMonth-oldMonth));//计算相差多少了个月
System.out.println(oldDateStr+"与今天"+curDate+"相差了"+betweenMonth+"个月");
获得指定日期的天数差:
DateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Date date = new Date();
String format = dft.format(date);
Long num = 0L;
try {
Date star = dft.parse(createTime);//开始时间
Date endDay=dft.parse(format);//结束时间
Long starTime=star.getTime();
Long endTime=endDay.getTime();
num=endTime-starTime;//时间戳相差的毫秒数
System.out.println("相差天数为:"+num/24/60/60/1000);//除以一天的毫秒数
} catch (ParseException e) {
e.printStackTrace();
}
两个时间的比较:
使用Date.before(),Date.after()和Date.equals()
if (c.getTime().after(nowDay)){//如果质保到达的时间在当前的时间后面 即为true
System.out.println("true = " + true);
}
按照指定格式展示年月
//转换一下年月格式
DateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd");
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Date date = null;
String inputText = map.get("time")== null ? "" : map.get("time");
try {
date = inputFormat.parse(inputText);
}catch (Exception e){
e.printStackTrace();
}
String outputText = outputFormat.format(date);