Java中常用的获取从当前月开始的前第i个月、取结束时间与开始时间相差多少个月份等的方法
@RunWith(SpringRunner.class)
@SpringBootTest
public class DateTest {
@Test
public void test(){
DateFormat dfs = new SimpleDateFormat("yyyy-MM");
String date1 = dfs.format(new Date(Long.valueOf("1546327530000")));
String date2 = dfs.format(new Date(Long.valueOf("1559373930000")));
// getLastMonths(1);
// getDifference(date1,date2);
// getMouths(new Date(),1);
getEveryDay(new Date(),7L);
}
/**
* 获取从当前月开始的前第i个月
* @param i
* @return
*/
public String getLastMonths(int i) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -i);
Date m = c.getTime();
System.out.println(sdf.format(m));
return sdf.format(m);
}
/**
* 获取结束时间与开始时间相差多少个月份
* @param start
* @param end
* @return
*/
public int getDifference(String start, String end) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String str1 = start.substring(0, 7);
String str2 = end.substring(0, 7);
Calendar bef = Calendar.getInstance();
Calendar aft = Calendar.getInstance();
try {
bef.setTime(sdf.parse(str1));
aft.setTime(sdf.parse(str2));
} catch (ParseException e) {
e.printStackTrace();
}
int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
System.out.println(Math.abs(month + result));
return Math.abs(month + result);
}
/**
* 获取某个月份在i个月之前的月份
* @param date
* @param i
* @return
*/
public String getMouths(Date date,int i){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, Integer.valueOf("-"+i));
Date m = c.getTime();
String mon = format.format(m);
System.out.println("过去一个月:"+mon);
return mon;
}
/**
* 计算两个时间点相差多少天、多少小时、多少分钟
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public Long getDay(Date date1,Date date2) throws ParseException {
long nd = 1000 * 24 * 60 * 60;//每天毫秒数
long nh = 1000 * 60 * 60;//每小时毫秒数
long nm = 1000 * 60;//每分钟毫秒数
long diff = date2.getTime() - date1.getTime(); // 获得两个时间的毫秒时间差异
long day = diff / nd; // 计算差多少天
long hour = diff % nd / nh; // 计算差多少小时
long min = diff % nd % nh / nm; // 计算差多少分钟
return day;
}
/**
* 计算某个时间点在i天之前的时间点
*
* @param date
* @param i
* @return
*/
public String getEveryDay(Date date,Long i){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, Integer.valueOf("-"+i));
Date d = c.getTime();
String day = format.format(d);
System.out.println("过去七天:"+day);
return day;
}
}
关注我的技术公众号,每天都有优质技术文章推送。
微信扫一扫下方二维码即可关注:
尚未佩妥剑,转眼便江湖,愿历尽千帆,归来仍少年