1. 程式人生 > 其它 >java常見的時間工具類-DateUtils

java常見的時間工具類-DateUtils

package com.app.common.util;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;

public class DateUtils {

/**
* 僅顯示年月日,例如 2015-08-11.
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 顯示年月日時分秒,例如 2015-08-11 09:51:53.
*/
public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

/**
* 僅顯示時分秒,例如 09:51:53.
*/
public static final String TIME_FORMAT = "HH:mm:ss";

/**
* 每天的毫秒數 8640000.
*/
public static final long MILLISECONDS_PER_DAY = 86400000L;

/**
* 每週的天數.
*/
public static final long DAYS_PER_WEEK = 7L;

/**
* 每小時毫秒數.
*/
public static final long MILLISECONDS_PER_HOUR = 3600000L;

/**
* 每分鐘秒數.
*/
public static final long SECONDS_PER_MINUTE = 60L;

/**
* 每小時秒數.
*/
public static final long SECONDS_PER_HOUR = 3600L;

/**
* 每天秒數.
*/
public static final long SECONDS_PER_DAY = 86400L;

/**
* 每個月秒數,預設每月30天.
*/
public static final long SECONDS_PER_MONTH = 2592000L;

/**
* 每年秒數,預設每年365天.
*/
public static final long SECONDS_PER_YEAR = 31536000L;

/**
* 常用的時間格式.
*/
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

/**
* 得到當前日期字串.
* @return String 日期字串,例如2015-08-11
* @since 1.0
*/
public static String getDate() {
return getDate(DateUtils.DATE_FORMAT);
}

/**
* 得到當前時間字串.
* @return String 時間字串,例如 09:51:53
* @since 1.0
*/
public static String getTime() {
return formatDate(new Date(), DateUtils.TIME_FORMAT);
}

/**
* 得到當前日期和時間字串.
* @return String 日期和時間字串,例如 2015-08-11 09:51:53
* @since 1.0
*/
public static String getDateTime() {
return formatDate(new Date(), DateUtils.DATETIME_FORMAT);
}

/**
* 獲取當前時間指定格式下的字串.
* @param pattern
* 轉化後時間展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
* @return String 格式轉換之後的時間字串.
* @since 1.0
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}

/**
* 獲取指定日期的字串格式.
* @param date 需要格式化的時間,不能為空
* @param pattern 時間格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
* @return String 格式轉換之後的時間字串.
* @since 1.0
*/
public static String getDate(Date date, String pattern) {
return DateFormatUtils.format(date, pattern);
}

/**
* 獲取日期時間字串,預設格式為(yyyy-MM-dd).
* @param date 需要轉化的日期時間
* @param pattern 時間格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等
* @return String 格式轉換後的時間字串
* @since 1.0
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT);
}
return formatDate;
}

/**
* 獲取當前年份字串.
* @return String 當前年份字串,例如 2015
* @since 1.0
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}

/**
* 獲取當前月份字串.
* @return String 當前月份字串,例如 08
* @since 1.0
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}

/**
* 獲取當前天數字符串.
* @return String 當前天數字符串,例如 11
* @since 1.0
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}

/**
* 獲取當前星期字串.
* @return String 當前星期字串,例如星期二
* @since 1.0
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}

/**
* 將日期型字串轉換為日期格式.
* 支援的日期字串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
* @param str
* @return Date
* @since 1.0
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}

/**
* 獲取當前日期與指定日期相隔的天數.
* @param date 給定的日期
* @return long 日期間隔天數,正數表示給定日期在當前日期之前,負數表示在當前日期之後
* @since 1.0
*/
public static long pastDays(Date date) {
// 將指定日期轉換為yyyy-MM-dd格式
date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT));
// 當前日期轉換為yyyy-MM-dd格式
Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
long t=0;
if(date!=null&&currentDate!=null){
t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
}
return t;
}

/**
* 獲取當前日期指定天數之後的日期.
* @param num 相隔天數
* @return Date 日期
* @since 1.0
*/
public static Date nextDay(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num);
return curr.getTime();
}

/**
* 獲取當前日期指定月數之後的日期.
* @param num 間隔月數
* @return Date 日期
* @since 1.0
*/
public static Date nextMonth(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num);
return curr.getTime();
}

/**
* 獲取當前日期指定年數之後的日期.
* @param num 間隔年數
* @return Date 日期
* @since 1.0
*/
public static Date nextYear(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + num);
return curr.getTime();
}

/**
* 將 Date 日期轉化為 Calendar 型別日期.
* @param date 給定的時間,若為null,則預設為當前時間
* @return Calendar Calendar物件
* @since 1.0
*/
public static Calendar getCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
// calendar.setFirstDayOfWeek(Calendar.SUNDAY);//每週從週日開始
// calendar.setMinimalDaysInFirstWeek(1); // 設定每週最少為1天
if (date != null) {
calendar.setTime(date);
}
return calendar;
}

/**
* 計算兩個日期之間相差天數.
* @param start 計算開始日期
* @param end 計算結束日期
* @return long 相隔天數
* @since 1.0
*/
public static long getDaysBetween(Date start, Date end) {
// 將指定日期轉換為yyyy-MM-dd格式
start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT));
// 當前日期轉換為yyyy-MM-dd格式
end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT));

long diff=0;
if(start!=null&&end!=null) {
diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
}
return diff;
}

/**
* 計算兩個日期之前相隔多少周.
* @param start 計算開始時間
* @param end 計算結束時間
* @return long 相隔週數,向下取整
* @since 1.0
*/
public static long getWeeksBetween(Date start, Date end) {
return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK;
}

/**
* 獲取與指定日期間隔給定天數的日期.
* @param specifiedDay 給定的字串格式日期,支援的日期字串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss",
* "yyyy/MM/dd HH:mm"
* @param num 間隔天數
* @return String 間隔指定天數之後的日期
* @since 1.0
*/
public static String getSpecifiedDayAfter(String specifiedDay, int num) {
Date specifiedDate = parseDate(specifiedDay);
Calendar c = Calendar.getInstance();
c.setTime(specifiedDate);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + num);
String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT);
return dayAfter;
}

/**
* 計算兩個日期之前間隔的小時數.
*
* @param date1
* 結束時間
* @param date2
* 開始時間
* @return String 相差的小時數,保留一位小數
* @since 1.0
*/
public static String dateMinus(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return "0";
}
Long r = date1.getTime() - date2.getTime();
DecimalFormat df = new DecimalFormat("#.0");
double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR;
return df.format(result);
}

/**
* 獲取當前季度 .
*
* @return Integer 當前季度數
* @since 1.0
*/
public static Integer getCurrentSeason() {
Calendar calendar = Calendar.getInstance();
Integer month = calendar.get(Calendar.MONTH) + 1;
int season = 0;
if (month >= 1 && month <= 3) {
season = 1;
} else if (month >= 4 && month <= 6) {
season = 2;
} else if (month >= 7 && month <= 9) {
season = 3;
} else if (month >= 10 && month <= 12) {
season = 4;
}
return season;
}

/**
* 將以秒為單位的時間轉換為其他單位.
*
* @param seconds
* 秒數
* @return String 例如 16分鐘前、2小時前、3天前、4月前、5年前等
* @since 1.0
*/
public static String getIntervalBySeconds(long seconds) {
StringBuffer buffer = new StringBuffer();
if (seconds < SECONDS_PER_MINUTE) {
buffer.append(seconds).append("秒前");
} else if (seconds < SECONDS_PER_HOUR) {
buffer.append(seconds / SECONDS_PER_MINUTE).append("分鐘前");
} else if (seconds < SECONDS_PER_DAY) {
buffer.append(seconds / SECONDS_PER_HOUR).append("小時前");
} else if (seconds < SECONDS_PER_MONTH) {
buffer.append(seconds / SECONDS_PER_DAY).append("天前");
} else if (seconds < SECONDS_PER_YEAR) {
buffer.append(seconds / SECONDS_PER_MONTH).append("月前");
} else {
buffer.append(seconds / DateUtils.SECONDS_PER_YEAR).append("年前");
}
return buffer.toString();
}

/**
*
* getNowTimeBefore(記錄時間相當於目前多久之前)
*
* @param seconds
* 秒
* @return
* @exception @since
* 1.0
* @author rlliu
*/
public static String getNowTimeBefore(long seconds) {
StringBuffer buffer = new StringBuffer();
buffer.append("上傳於");
if (seconds < 3600) {
buffer.append((long) Math.floor(seconds / 60.0)).append("分鐘前");
} else if (seconds < 86400) {
buffer.append((long) Math.floor(seconds / 3600.0)).append("小時前");
} else if (seconds < 604800) {
buffer.append((long) Math.floor(seconds / 86400.0)).append("天前");
} else if (seconds < 2592000) {
buffer.append((long) Math.floor(seconds / 604800.0)).append("周前");
} else if (seconds < 31104000) {
buffer.append((long) Math.floor(seconds / 2592000.0)).append("月前");
} else {
buffer.append((long) Math.floor(seconds / 31104000.0)).append("年前");
}
return buffer.toString();
}

/**
*
* getMonthsBetween(查詢兩個日期相隔的月份)
*
* @param startDate 開始日期1 (格式yyyy-MM-dd)
* @param endDate 截止日期2 (格式yyyy-MM-dd)
* @return
*/
public static int getMonthsBetween(String startDate, String endDate) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(DateUtils.parseDate(startDate));
c2.setTime(DateUtils.parseDate(endDate));
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
return Math.abs(year * 12 + month);
}

/**
*
* getDayOfWeek(獲取當前日期是星期幾)
*
* @param dateStr 日期
* @return 星期幾
*/
public static String getDayOfWeek(String dateStr) {
String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Date date = parseDate(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int num = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return weekOfDays[num];
}

/**
* sns 格式 如幾秒前,幾分鐘前,幾小時前,幾天前,幾個月前,幾年後, ... 精細,類如某個明星幾秒鐘之前發表了一篇微博
*
* @param createTime
* @return
*/
public static String snsFormat(long createTime) {
long now = System.currentTimeMillis() / 1000;
long differ = now - createTime / 1000;
String dateStr = "";
if (differ <= 60) {
dateStr = "剛剛";
} else if (differ <= 3600) {
dateStr = (differ / 60) + "分鐘前";
} else if (differ <= 3600 * 24) {
dateStr = (differ / 3600) + "小時前";
} else if (differ <= 3600 * 24 * 30) {
dateStr = (differ / (3600 * 24)) + "天前";
} else {
Date date = new Date(createTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dateStr = sdf.format(date);
}
return dateStr;
}

/**
* 得到UTC時間,型別為字串,格式為"yyyy-MM-dd HH:mm"
* 如果獲取失敗,返回null
* @return
*/
public static String getUTCTimeStr() {
StringBuffer UTCTimeBuffer = new StringBuffer();
// 1、取得本地時間:
Calendar cal = Calendar.getInstance() ;
// 2、取得時間偏移量:
int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
// 3、取得夏令時差:
int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
// 4、從本地時間裡扣除這些差量,即可以取得UTC時間:
cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ;
UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ;
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.parse(UTCTimeBuffer.toString()) ;
return UTCTimeBuffer.toString() ;
}catch(ParseException e)
{
e.printStackTrace() ;
}
return null ;
}
}