java處理日期的工具類DateUtil
更新時(shí)間:2020年10月21日 10:14:39 作者:leo825...
這篇文章主要為大家詳細(xì)介紹了java處理日期的工具類DateUtil,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
java中處理日期的工具類DateUtil,供大家參考,具體內(nèi)容如下
package com.leo.demo.othertest;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
/**
* 時(shí)間工具類
*/
public final class DateUtil {
private static Logger logger = (Logger) LoggerFactory.getLogger(DateUtil.class);
/**
* 日期格式
*/
public interface DATE_PATTERN {
String HHMMSS = "HHmmss";
String HH_MM_SS = "HH:mm:ss";
String HH_MM = "HH:mm";
String YYYY = "yyyy";
String YYYYMMDD = "yyyyMMdd";
String YYYYMM = "yyyyMM";
String YYYY_MM_DD = "yyyy-MM-dd";
String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
}
/**
* 獲取當(dāng)前時(shí)間
*
* @return Timestamp對(duì)象
*/
public static Timestamp getCurrontTime() {
Timestamp sqlTimestamp = new Timestamp(new Date().getTime());
return sqlTimestamp;
}
/**
* 將Date類型轉(zhuǎn)換成String類型
*
* @param date Date對(duì)象
* @return 形如:"yyyy-MM-dd HH:mm:ss"
*/
public static String date2String(Date date) {
return date2String(date, DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
}
/**
* 將Date按格式轉(zhuǎn)化成String
*
* @param date Date對(duì)象
* @param pattern 日期類型
* @return String
*/
public static String date2String(Date date, String pattern) {
if (date == null || pattern == null) {
return null;
}
return new SimpleDateFormat(pattern).format(date);
}
/**
* 將String類型轉(zhuǎn)換成Date類型
*
* @param date Date對(duì)象
* @return
*/
public static Date string2Date(String date) {
SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
try {
return format.parse(date);
} catch (ParseException e) {
return null;
}
}
/**
* 獲取某日期N天后的日期
*
* @param datestr
* @param day
* @return
*/
public static Date getBeforeAfterDate(String datestr, int day) {
SimpleDateFormat df = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
java.sql.Date olddate = null;
try {
df.setLenient(false);
olddate = new java.sql.Date(df.parse(datestr).getTime());
} catch (ParseException e) {
throw new RuntimeException("日期轉(zhuǎn)換錯(cuò)誤");
}
Calendar cal = new GregorianCalendar();
cal.setTime(olddate);
int Year = cal.get(Calendar.YEAR);
int Month = cal.get(Calendar.MONTH);
int Day = cal.get(Calendar.DAY_OF_MONTH);
int NewDay = Day + day;
cal.set(Calendar.YEAR, Year);
cal.set(Calendar.MONTH, Month);
cal.set(Calendar.DAY_OF_MONTH, NewDay);
return new Date(cal.getTimeInMillis());
}
/**
* @return
* @Description: 獲取當(dāng)前日期的前一天
* @ReturnType String
* @author: liyl
* @Created 2015年11月13日 下午5:11:14
*/
public static Date currentBeforeDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, -1);
return calendar.getTime();
}
/**
* @return
* @Description: 獲取當(dāng)前日期的后一天
* @ReturnType Date
* @author: liyl
* @Created 2015年11月13日 下午5:14:54
*/
public static Date currentNextDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
/**
* 獲取指定日期星期幾(int)
*
* @param dt
* @return
*/
public static int getWeekOfInt(Date dt) {
int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return weekDays[w];
}
/**
* 獲取指定日期星期幾
*
* @param dt
* @return
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return weekDays[w];
}
/**
* 時(shí)間比大小
*
* @param DATE1
* @param DATE2
* @param pattern
* @return
*/
public static int compareDate(String DATE1, String DATE2, String pattern) {
DateFormat df = new SimpleDateFormat(pattern);
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
System.out.println("dt1 在dt2前");
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
System.out.println("dt1在dt2后");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
/**
* 在一個(gè)時(shí)間上加上或減去分鐘
*
* @param date long
* @param i int
* @return Date
*/
public static Date addOrMinusMinutes(Date date, int i) {
Date rtn = null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.MINUTE, i);
rtn = cal.getTime();
return rtn;
}
/**
* 按照指定格式返回格式好的當(dāng)前日期
*
* @param dateFormat 默認(rèn)yyyy-MM-dd
* @return
*/
public static String getCurrentDateString(String dateFormat) {
return DateUtil.format(new Date(), DATE_PATTERN.YYYY_MM_DD);
}
/**
* 說(shuō)明 將日期格式化字符串,為null的返回空字符串
*
* @param date
* @return
*/
public static String format(Date date) {
if (null == date) return "";
SimpleDateFormat sf = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD);
return sf.format(date);
}
/**
* 說(shuō)明 將日期格式化字符串,為null的返回空字符串
*
* @param date 日期
* @param dateFormat 格式化字符串,比如:yyyy-MM-dd
* @return
*/
public static String format(Date date, String dateFormat) {
if (null == dateFormat || "".equals(dateFormat)) return DateUtil.format(date);
if (null == date) return "";
SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
return sf.format(date);
}
/**
* @param source 要進(jìn)行解析的源字符串
* @return
* @說(shuō)明 將指定的字符串格解析成日期類型,格式默認(rèn)為:yyyy-MM-dd
*/
public static Date parase(String source) {
SimpleDateFormat sf = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD);
try {
return sf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* @param source 要進(jìn)行解析的源字符串
* @param dateFormat 要解析的日期格式。
* @return
* @說(shuō)明 將指定的字符串格解析成日期類型 例:如果日期source=20131210,則dateFormat應(yīng)為:yyyyMMdd,兩個(gè)應(yīng)對(duì)應(yīng)
*/
public static Date parase(String source, String dateFormat) {
SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
try {
return sf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* @param date
* @param days
* @說(shuō)明 對(duì)指定的日期增加或減少指定的天數(shù)
*/
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
* @param date
* @param days
* @說(shuō)明 對(duì)指定的日期增加或減少指定的天數(shù)
*/
public static Calendar addDays(Calendar date, int days) {
date.add(Calendar.DAY_OF_MONTH, days);
return date;
}
/**
* @param date
* @param months
* @return
* @說(shuō)明 對(duì)指定的日期增加或減少指定的月數(shù)
*/
public static Date addMonths(Date date, int months) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, months);
return cal.getTime();
}
/**
* @param date
* @param months
* @return
* @說(shuō)明 對(duì)指定的日期增加或減少指定的月數(shù)
*/
public static Calendar addMonths(Calendar date, int months) {
date.add(Calendar.MONTH, months);
return date;
}
/**
* @param date
* @param hours
* @return
* @說(shuō)明 對(duì)指定的日期增加或減少指定的小時(shí)數(shù)
*/
public static Date addHours(Date date, int hours) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
return cal.getTime();
}
/**
* 對(duì)指定的日期增加或減少指定的小時(shí)數(shù)
*
* @param date
* @param hours
* @return
*/
public static Calendar addHours(Calendar date, int hours) {
date.add(Calendar.HOUR_OF_DAY, hours);
return date;
}
/**
* 以字符串形式返回當(dāng)前時(shí)間的毫秒數(shù)
*
* @return
*/
public static String getTimeMillions() {
Calendar cal = Calendar.getInstance();
long lt = cal.getTimeInMillis();
return String.valueOf(lt);
}
/**
* 獲取當(dāng)前月的第一天
*
* @return 當(dāng)前月的第一天
*/
public static String getMonthFirstDay() {
SimpleDateFormat df = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD);
Calendar calendar = Calendar.getInstance();
Date theDate = calendar.getTime();
GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
gcLast.setTime(theDate);
gcLast.set(Calendar.DAY_OF_MONTH, 1);
String day_first = df.format(gcLast.getTime());
StringBuffer str = new StringBuffer().append(day_first);
return str.toString();
}
/**
* 獲取當(dāng)前月的最后一天
*
* @return 當(dāng)前月的最后一天
*/
public static String getMonthLastDay() {
Calendar calendar = Calendar.getInstance();
// 最后一天
int maxday = calendar.getActualMaximum(Calendar.DATE);
calendar.set(Calendar.DATE, maxday);
SimpleDateFormat df = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD);
Date theDate = calendar.getTime();
String s = df.format(theDate);
StringBuffer str = new StringBuffer().append(s);
return str.toString();
}
/**
* 獲取當(dāng)前月的第一天,精確到時(shí)分秒
*
* @return 當(dāng)前月的第一天,精確到時(shí)分秒
*/
public static Date getFirstDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
return date;
}
/**
* 獲得往數(shù)據(jù)庫(kù)字段類型為Date型時(shí),插入的時(shí)間
*
* @param date 默認(rèn)為當(dāng)前日期,如果為空時(shí) 方法會(huì)自動(dòng)new Date()
* @param dateFormat 默認(rèn)為yyyy-MM-dd
* @return
*/
public static java.sql.Date paraseSqlDate(String date, String dateFormat) {
try {
if (date == null || date.length() == 0) {
return new java.sql.Date(new Date().getTime());
} else {
if (dateFormat == null) dateFormat = DateUtil.DATE_PATTERN.YYYY_MM_DD;
SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
Date d = sf.parse(date);
return new java.sql.Date(d.getTime());
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 將日期按照特定格式轉(zhuǎn)換成字符串
*
* @param date
* @param pattern
* @return
*/
public static String formatString(Date date, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(date);
}
/**
* 將日期字符串轉(zhuǎn)換為日期
*
* @param strDate
* @param mask
* @return
* @throws ParseException
*/
public static Timestamp convertStringToTimestamp(String strDate, String mask) throws ParseException {
SimpleDateFormat df;
Date date = null;
df = new SimpleDateFormat(mask);
try {
date = df.parse(strDate);
return new Timestamp(date.getTime());
} catch (ParseException pe) {
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}
}
/**
* 月份相加 add by yuanjq
*
* @param timest1
* @param month
* @return
*/
public static Timestamp DateAddMonth(Timestamp timest1, int month) {
Calendar cal = Calendar.getInstance();
cal.setTime(timest1);
cal.add(Calendar.MONTH, month);
return new Timestamp(cal.getTimeInMillis());
}
/**
* 對(duì)輸入的日期進(jìn)行格式化, 如果輸入的日期是null則返回空串.
* FrameWork使用
*
* @param dtDate java.sql.Timestamp 需要進(jìn)行格式化的日期字符串
* @param strFormatTo String 要轉(zhuǎn)換的日期格式
* @return String 經(jīng)過格式化后的字符串
*/
public static String getFormattedDate(java.sql.Timestamp dtDate,
String strFormatTo) {
if (dtDate == null) {
return "";
}
if (dtDate.equals(new java.sql.Timestamp(0))) {
return "";
}
String newStrFormateTo = strFormatTo;
newStrFormateTo = newStrFormateTo.replace('/', '-');
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
if (Integer.parseInt(formatter.format(dtDate)) < 1900) {
return "";
} else {
formatter = new SimpleDateFormat(newStrFormateTo);
return formatter.format(dtDate);
}
}
/**
* 獲取當(dāng)前時(shí)間年月日
*
* @return
*/
public static String getCurrentDateYMR() {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN.YYYYMMDD);
return sdf.format(System.currentTimeMillis());
}
/**
* 根據(jù)字符串以及格式化方式獲取date對(duì)象
*
* @param strDate
* @param strFormat
* @return
* @throws ParseException
*/
public static Date getDate(String strDate, String strFormat) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(strFormat);
Date date = format.parse(strDate);
return date;
}
/**
* 根據(jù)字符串以及格式化方式獲取時(shí)間戳
*
* @param strDate
* @param strFormat
* @return
* @throws ParseException
*/
public static Timestamp getTimestamp(String strDate, String strFormat) throws ParseException {
Date date = getDate(strDate, strFormat);
Timestamp timestamp = new Timestamp(date.getTime());
return timestamp;
}
/**
* 根據(jù)Date獲取格式化后的字符串
*
* @param date
* @param strFormat
* @return
* @throws ParseException
*/
public static String getStringDate(Date date, String strFormat) throws ParseException {
if (date == null) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat(strFormat);
String strDate = format.format(date);
return strDate;
}
/**
* 根據(jù)時(shí)間戳格式化時(shí)間
*
* @param timestamp
* @param strFormat
* @return
* @throws ParseException
*/
public static String getStringTimestamp(Timestamp timestamp, String strFormat) throws ParseException {
if (timestamp == null) {
return "";
}
String strTimestamp = getStringDate((Date) timestamp, strFormat);
return strTimestamp;
}
/**
* 根據(jù)時(shí)間戳偏移幾個(gè)月
*
* @param timestamp
* @param months
* @return
* @throws ParseException
*/
public static Timestamp addMonth(Timestamp timestamp, int months) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.MONTH, months);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間戳偏移幾年
*
* @param timestamp
* @param years
* @return
* @throws ParseException
*/
public static Timestamp addYear(Timestamp timestamp, int years) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.YEAR, years);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間戳偏移幾天
*
* @param timestamp
* @param days
* @return
* @throws ParseException
*/
public static Timestamp addDay(Timestamp timestamp, int days) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.DAY_OF_MONTH, days);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間戳偏移幾小時(shí)
*
* @param timestamp
* @param hours
* @return
* @throws ParseException
*/
public static Timestamp addHour(Timestamp timestamp, int hours) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.HOUR_OF_DAY, hours);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間戳偏移幾分鐘
*
* @param timestamp
* @param minutes
* @return
* @throws ParseException
*/
public static Timestamp addMinute(Timestamp timestamp, int minutes) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.MINUTE, minutes);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間戳偏移幾秒鐘
*
* @param timestamp
* @param seconds
* @return
* @throws ParseException
*/
public static Timestamp addSecond(Timestamp timestamp, int seconds) throws ParseException {
GregorianCalendar grc = new GregorianCalendar();
grc.setTime((Date) timestamp);
grc.add(GregorianCalendar.SECOND, seconds);
return new Timestamp(grc.getTime().getTime());
}
/**
* 根據(jù)時(shí)間的毫秒值格式化時(shí)間
*
* @param time
* @param strFormat
* @return
* @throws ParseException
*/
public static String getTime(String time, String strFormat) throws ParseException {
Timestamp endLogDateFormated = getTimestamp(time, strFormat);
String sTime = getStringTimestamp(endLogDateFormated, DATE_PATTERN.YYYYMMDD);
return sTime;
}
/**
* 轉(zhuǎn)換時(shí)間格式化方式
*
* @param time
* @param strFormat
* @return
* @throws ParseException
*/
public static String getTimeNew(String time, String strFormat) throws ParseException {
Timestamp endLogDateFormated = getTimestamp(time, strFormat);
String sTime = getStringTimestamp(endLogDateFormated, DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
return sTime;
}
/**
* 根據(jù)傳入的日期字符串轉(zhuǎn)換成相應(yīng)的日期對(duì)象,
* 如果字符串為空或不符合日期格式,則返回當(dāng)前時(shí)間。
* FrameWork使用
*
* @param strDate String 日期字符串
* @return java.sql.Timestamp 日期對(duì)象
*/
public static java.sql.Timestamp getDateByString(String strDate) {
if (strDate.trim().equals("")) {
return getCurrentDate();
}
try {
strDate = getFormattedDate(strDate, DATE_PATTERN.YYYY_MM_DD_HH_MM_SS) + ".000000000";
return java.sql.Timestamp.valueOf(strDate);
} catch (Exception ex) {
return getCurrentDate();
}
}
/**
* 獲取當(dāng)前數(shù)據(jù)庫(kù)時(shí)間
*
* @return
*/
public static Timestamp getCurrentDate() {
try {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_PATTERN.YYYY_MM_DD_HH_MM_SS + ".0");
return Timestamp.valueOf(formatter.format(new Date()));
} catch (Exception e) {
return null;
}
}
/**
* 對(duì)輸入的日期字符串進(jìn)行格式化,
* 如果輸入的是0000/00/00 00:00:00則返回空串.
* FrameWork使用
*
* @param strDate String 需要進(jìn)行格式化的日期字符串
* @param strFormatTo String 要轉(zhuǎn)換的日期格式
* @return String 經(jīng)過格式化后的字符串
*/
public static String getFormattedDate(String strDate, String strFormatTo) {
if ((strDate == null) || strDate.trim().equals("")) {
return "";
}
strDate = strDate.replace('/', '-');
strFormatTo = strFormatTo.replace('/', '-');
if (strDate.equals("0000-00-00 00:00:00") ||
strDate.equals("1800-01-01 00:00:00")) {
return "";
}
String formatStr = strFormatTo; //"yyyyMMdd";
if (strDate.trim().equals("")) { //(strDate == null) ||
return "";
}
switch (strDate.trim().length()) {
case 6:
if (strDate.substring(0, 1).equals("0")) {
formatStr = "yyMMdd";
} else {
formatStr = "yyyyMM";
}
break;
case 8:
formatStr = "yyyyMMdd";
break;
case 10:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd";
} else {
formatStr = "yyyy-MM-dd";
}
break;
case 11:
if (strDate.getBytes().length == 14) {
formatStr = "yyyy年MM月dd日";
} else {
return "";
}
break;
case 14:
formatStr = "yyyyMMddHHmmss";
break;
case 19:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd HH:mm:ss";
} else {
formatStr = "yyyy-MM-dd HH:mm:ss";
}
break;
case 21:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd HH:mm:ss.S";
} else {
formatStr = "yyyy-MM-dd HH:mm:ss.S";
}
break;
default:
return strDate.trim();
}
try {
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(formatter.parse(strDate));
formatter = new SimpleDateFormat(strFormatTo);
return formatter.format(calendar.getTime());
} catch (Exception e) {
return "";
}
}
/**
* 處理微信日期
*
* @param date
* @return
*/
public static String dealWechatDate(String date) {
String result;
if (date == null || "".equals(date)) {
result = date;
} else if (date.indexOf(".") > -1) {
result = date.replace(".", "-");
} else if (date.indexOf("年") > -1) {
result = date.replace("年", "-").replace("月", "-").replace("日", "");
} else if (date.indexOf("-") > -1) {
result = date.replace("年", "-").replace("月", "-").replace("日", "");
} else {
result = date;
}
return result;
}
/**
* 獲取兩個(gè)日期相差的月數(shù)
*
* @param d1 較大的日期
* @param d2 較小的日期
* @return 如果d1>d2返回 月數(shù)差 否則返回0
*/
public static int monthsBetween(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
if (c1.getTimeInMillis() < c2.getTimeInMillis()) return 0;
int year1 = c1.get(Calendar.YEAR);
int year2 = c2.get(Calendar.YEAR);
int month1 = c1.get(Calendar.MONTH);
int month2 = c2.get(Calendar.MONTH);
int day1 = c1.get(Calendar.DAY_OF_MONTH);
int day2 = c2.get(Calendar.DAY_OF_MONTH);
// 獲取年的差值 假設(shè) d1 = 2015-8-16 d2 = 2011-9-30
int yearInterval = year1 - year2;
// 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 這樣就得到了相差的年數(shù)
if (month1 < month2 || month1 == month2 && day1 < day2) yearInterval--;
// 獲取月數(shù)差值
int monthInterval = (month1 + 12) - month2;
if (day1 < day2) monthInterval--;
monthInterval %= 12;
return yearInterval * 12 + monthInterval;
}
/**
* 計(jì)算date2 - date1之間相差的天數(shù)
*
* @param date1
* @param date2
* @return 如果d1>d2返回 月數(shù)差 否則返回0
*/
public static int daysBetween(Date date1, Date date2) {
DateFormat sdf = new SimpleDateFormat(DATE_PATTERN.YYYYMMDD);
Calendar cal = Calendar.getInstance();
try {
Date d1 = sdf.parse(date2String(date1, DATE_PATTERN.YYYYMMDD));
Date d2 = sdf.parse(date2String(date2, DATE_PATTERN.YYYYMMDD));
cal.setTime(d1);
long time1 = cal.getTimeInMillis();
cal.setTime(d2);
long time2 = cal.getTimeInMillis();
return Integer.parseInt(String.valueOf((time2 - time1) / 86400000L));
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 計(jì)算date2 - date1之間相差的分鐘
*
* @param date1
* @param date2
* @return
*/
@SuppressWarnings("deprecation")
public static int minutesBetween(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
// date1.setSeconds(0);
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
if (time2 - time1 <= 0) {
return 0;
} else {
return Integer.parseInt(String.valueOf((time2 - time1) / 60000L)) + 1;
}
}
/**
* 計(jì)算date2 - date1之間相差的秒
*
* @param date1
* @param date2
* @return
*/
@SuppressWarnings("deprecation")
public static int secondBetween(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
// date1.setSeconds(0);
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
if (time2 - time1 <= 0) {
return 0;
} else {
return Integer.parseInt(String.valueOf((time2 - time1) / 1000L)) + 1;
}
}
/**
* 計(jì)算date2 - date1之間相差的毫秒
*
* @param date1
* @param date2
* @return
*/
@SuppressWarnings("deprecation")
public static int millisecondBetween(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
if (time2 - time1 <= 0) {
return 0;
} else {
return Integer.parseInt(String.valueOf((time2 - time1)));
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- 教你如何使用Java多線程編程LockSupport工具類
- Java常用工具類庫(kù)——Hutool的使用簡(jiǎn)介
- 淺談java如何生成分享海報(bào)工具類
- java中封裝JDBC工具類的實(shí)例分析
- Java編寫超時(shí)工具類實(shí)例講解
- Java JDBC自定義封裝工具類的步驟和完整代碼
- java中金額元轉(zhuǎn)萬(wàn)元工具類的實(shí)例
- Java利用POI讀寫Excel文件工具類
- java讀取簡(jiǎn)單excel通用工具類
- Java身份證號(hào)碼校驗(yàn)工具類詳解
- java身份證合法性校驗(yàn)工具類實(shí)例代碼
- Java實(shí)現(xiàn)RSA加密工具類
- Java基礎(chǔ)之顏色工具類(超詳細(xì)注釋)
相關(guān)文章
Java+MyBatis+MySQL開發(fā)環(huán)境搭建流程詳解
Java的MyBatis框架提供了強(qiáng)大的數(shù)據(jù)庫(kù)操作支持,這里我們先在本地的開發(fā)環(huán)境中上手,來(lái)看一下Java+MyBatis+MySQL開發(fā)環(huán)境搭建流程詳2016-06-06
spring boot集成rabbitmq的實(shí)例教程
這篇文章主要給大家介紹了關(guān)于spring boot集成rabbitmq的相關(guān)資料,springboot集成RabbitMQ非常簡(jiǎn)單,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
Java Swing中JDialog實(shí)現(xiàn)用戶登陸UI示例
這篇文章主要介紹了Java Swing中JDialog實(shí)現(xiàn)用戶登陸UI功能,結(jié)合完整實(shí)例形式分析了Swing使用JDialog實(shí)現(xiàn)用戶登陸UI界面窗口功能的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
java中Hutool工具類的常見使用場(chǎng)景詳解
在日常開發(fā)中,我們會(huì)使用很多工具類來(lái)提升項(xiàng)目開發(fā)的速度,而國(guó)內(nèi)用的比較多的 Hutool 框架,就是其中之一,本文我們就來(lái)介紹一下Hutool的具體使用吧2023-12-12
Java數(shù)據(jù)結(jié)構(gòu)之堆(優(yōu)先隊(duì)列)詳解
堆(優(yōu)先隊(duì)列)是一種典型的數(shù)據(jù)結(jié)構(gòu),其形狀是一棵完全二叉樹,一般用于求解topk問題。本文將利用Java語(yǔ)言實(shí)現(xiàn)堆,感興趣的可以學(xué)習(xí)一下2022-07-07
Java實(shí)現(xiàn)FIFO任務(wù)調(diào)度隊(duì)列策略
在工作中,很多高并發(fā)的場(chǎng)景中,我們會(huì)用到隊(duì)列來(lái)實(shí)現(xiàn)大量的任務(wù)請(qǐng)求。當(dāng)任務(wù)需要某些特殊資源的時(shí)候,我們還需要合理的分配資源,讓隊(duì)列中的任務(wù)高效且有序完成任務(wù)。本文將為大家介紹通過java實(shí)現(xiàn)FIFO任務(wù)調(diào)度,需要的可以參考一下2021-12-12

