package com.example.server.utils;
|
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.Calendar;
|
import java.util.Date;
|
|
public class TimeUtils {
|
|
public static String getTime(Date currentTime, Date firstTime) {
|
Calendar currentTimes = dataToCalendar(currentTime);//当前系统时间转Calendar类型
|
Calendar firstTimes = dataToCalendar(firstTime);//查询的数据时间转Calendar类型
|
int year = currentTimes.get(Calendar.YEAR) - firstTimes.get(Calendar.YEAR);//获取年
|
int month = currentTimes.get(Calendar.MONTH) - firstTimes.get(Calendar.MONTH);
|
int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH);
|
if (currentTime.after(firstTime)) {
|
String CountTime;
|
if (day < 0) {
|
month -= 1;
|
currentTimes.add(Calendar.MONTH, -1);
|
day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
|
}
|
if (month < 0) {
|
month = (month + 12) % 12;//获取月
|
year--;
|
}
|
if (year == 0 && month != 0) {
|
if (day == 0) {
|
CountTime = "" + month + "月";
|
} else {
|
CountTime = "" + month + "月" + day + "天";
|
}
|
|
} else if (month == 0 && year != 0) {
|
if (day == 0) {
|
CountTime = "" + year + "年";
|
} else {
|
CountTime = "" + year + "年" + day + "天";
|
}
|
} else if (year == 0 && month == 0) {
|
CountTime = "" + day + "天";
|
} else {
|
CountTime = "" + year + "年" + month + "月" + day + "天";
|
}
|
return CountTime;
|
} else {
|
return "-1天";
|
}
|
|
}
|
//Date类型转Calendar类型
|
|
|
public static Calendar dataToCalendar(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return calendar;
|
}
|
public static int daysBetween(Date date1, Date date2) throws ParseException {
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
Calendar cal = Calendar.getInstance();
|
cal.setTime(date1);
|
long time1 = cal.getTimeInMillis();
|
cal.setTime(date2);
|
long time2 = cal.getTimeInMillis();
|
long between_days = (time2 - time1) / (1000 * 3600 * 24);
|
String s = String.valueOf(between_days);
|
return Integer.parseInt(s);
|
}
|
public static long daysBetween(Date date1, Date date2, String type) {
|
long timeDiff = date2.getTime() - date1.getTime();
|
long seconds = timeDiff / 1000;
|
long minutes = seconds / 60;
|
long hours = minutes / 60;
|
long days = hours / 24;
|
long result = days;
|
return result;
|
}
|
|
public static Date dateAdd(Date date1, Integer diff, String type) {
|
Calendar cal = Calendar.getInstance();
|
cal.setTime(date1);//设置起时间
|
|
//cal.add(Calendar.YEAR, 1);//增加一年
|
//cal.add(Calendar.MONTH, 1);//增加一个月
|
cal.add(Calendar.DATE, diff);//增加一天
|
|
System.out.println("输出::" + cal.getTime());
|
return cal.getTime();
|
}
|
}
|