自訂時間工具類,自訂工具類
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);
}
}