自定义时间工具类

package com.jredu.ch10;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

/**
* 返回两个日期之间的相差天数
*
* @param d1
* @param d2
* @param patten
* @return
*/
public static int diffDay(String d1, String d2, String patten) {
int day = 0;
SimpleDateFormat format = new SimpleDateFormat(patten);
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(d1);
date2 = format.parse(d2);
long m = Math.abs(date1.getTime() - date2.getTime());
day = (int) (m / 1000 / 60 / 60 / 24);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}

/**
* 毫秒转日期
*
* @param m
* @return
*/
public static Date getDate(long m) {
return new Date(m);
}

/**
* 返回今天的日期
*/
public static Date getCurrentDate() {
return new Date();
}

/**
* 返回当前日期加减后的日期
*
* @param isPlus
* @param day
* @return
*/
public static Date getChangeDate(boolean isPlus, int day) {
// System.currentTimeMillis()获取当前时间的时间戳(自1970/01/01 00:00:00开始到当前经历的毫秒数)
long currentTime = System.currentTimeMillis();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = currentTime + (day * 24 * 60 * 60 * 1000);
} else {
// 减少日期
changeTime = currentTime - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 返回指定日期的加减天数
*
* @param isPlus
* @param day
* @param date
* @return
*/
public static Date getChangeDate(boolean isPlus, int day, Date date) {
long time = date.getTime();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = time + (day * 24 * 60 * 60 * 1000);
} else {
// 减少日期
changeTime = time - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 日期格式化
*
* @param date
* @param format
* @return
*/
public static String getFormatDate(Date date, String format) {
// 创建格式化日期对象
SimpleDateFormat sdf = new SimpleDateFormat(format);
// 将日期格式化后返回格式化字符串
return sdf.format(date);
}

}

原文地址:https://www.cnblogs.com/a5513633/p/6721405.html