//假设初始时间
String createDate = “2019-12-04 09:31:59”;
//将时间转换成时间格式
SimpleDateFormat sd = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date format = sd.parse(createDate);//入参时间
long time1 = format.getTime();
//使用日历类型进行日期控制
Calendar c1 = Calendar.getInstance();
c1.setTime(format);
c1.add(Calendar.DATE, 30);//得到初始时间后三十天(时间可调)
//将日历格式转换成时间戳格式
/**
//这段代码可以将时间格式转换成字符串
String date2 = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(new Date());
/
String temp = sd.format(c1.getTime());
System.out.println(temp);
//将时间戳格式转换成日期格式
Date parse = sd.parse(temp);
System.out.println(parse);
//将时间格式转换成毫秒值
long time = parse.getTime();
System.out.println(time);
//逻辑同上
Calendar c2 = Calendar.getInstance();
c2.setTime(format);
//获取指定时间前15天
c2.add(Calendar.DATE, -15);
String temp2 = sd.format(c2.getTime());
System.out.println(temp);
Date parse1 = sd.parse(temp2);
System.out.println(parse1);
long t1 = parse1.getTime();
System.out.println(time);
//这里就可以对时间进行计算
//注:除以10006060得到分钟
//不可以先将Long专程int再计算
Long l = (time - time1)/(1000606024);
Long l1 = (t1-time1)/(1000606024);
Long l2 = time1/(1000606024);
System.out.println(l);
System.out.println(l1);
System.out.println(l2);
输出结果
2020-01-03 09:31:59
Fri Jan 03 09:31:59 CST 2020
1578015119000
2020-01-03 09:31:59
Tue Nov 19 09:31:59 CST 2019
1578015119000
30
-15
18234
单元测试
String s = “2019-11-28 09:31:59”;
Utils utils = new Utils();
utils.checkDate(s);
测试结果
2019-12-28 09:31:59
Sat Dec 28 09:31:59 CST 2019
2019-11-13 09:31:59
Wed Nov 13 09:31:59 CST 2019
1573608719000