1. 程式人生 > >時間工具類DateUlits,判斷某一時間距離當前時間幾分鐘、幾小時、幾天前

時間工具類DateUlits,判斷某一時間距離當前時間幾分鐘、幾小時、幾天前

在我們開發中經常要對時間進行處理,把這些處理方法做成一個工具類是十分方面的,下面是我整理的一些時間處理的方法。

DateUlits方法目錄:

1、列印當前日期 2、輸入年-月-日  轉化為date型別 3、獲得一個 Date 物件例項 4、設定時間 5、獲取當前時間的前一天時間 6、獲取當前時間的後一天時間 7、判斷時間是否在某個時間區間內 8、判斷是否是今天 9、系統當前時間轉化為秒 10、字串轉換為對應日期 11、Date型別轉為指定格式的String型別 12、獲取前一天的時間的 年-月-日 13、獲取當前時間的 年-月-日 14、將當前時間秒的形式(1538129545)轉換為年月日-時分秒(2018-09-28 18:12:25) 15、將當前時間秒的形式(1538129545)轉換為年月日(2018-09-28) 16、當前時間秒的形式轉化為 HH:mm:ss 17、判斷目標日期距離當前日期多長時間 18、計算當前實際愛你和系統時間相差幾秒 19、獲取當天中午12點的時間(毫秒) 20、獲取下一天中午12點的時間(毫秒) 21、呼叫這個方法 你傳入一個日期 就能獲得 這個日期所在一週內的所有天數的一個List 22、根據日期獲得所在周的日期 23、把毫秒轉化成日期 24、獲取當天的開始時間 25、獲取當天的結束時間 26、獲取昨天的開始時間 27、獲取昨天的結束時間 28、獲取明天的開始時間 29、 獲取明天的結束時間 30、獲取本週的開始時間 31、獲取本週的結束時間 32、獲取本月的開始時間 33、獲取本月的結束時間 34、獲取本年的開始時間 35、 獲取本年的結束時間 36、獲取某個日期的開始時間 37、獲取某個日期的結束時間 38、獲取今年是哪一年 39、獲取本月是哪一月 40、兩個日期相減得到的天數 41、 兩個日期相減得到的毫秒數 42、獲取兩個日期中的最大日期 43、獲取兩個日期中的最小日期 44、返回某月該季度的第一個月 45、返回某個日期下幾天的日期 46、返回某個日期前幾天的日期 47、獲取某年某月到某年某月按天的切片日期集合(間隔天數的集合) 48、獲取某年某月按天切片日期集合(某個月間隔多少天的日期集合)

程式碼:

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class DateUtil {

	//列印當前日期
	public static String printDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	
	/**輸入年-月-日  轉化為date型別**/
	public static Date calendarToData(int year, int month, int day) {
		Calendar calendar = Calendar.getInstance();//日曆類的例項化
		calendar.set(year, month - 1, day);//設定日曆時間,月份必須減一
		Date date = calendar.getTime(); // 從一個 Calendar 物件中獲取 Date 物件
		return date;
	}
	
	/**獲得一個 Date 物件例項**/
	public static Calendar dataToCalendar(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	/**
	 * 設定時間
	 * @param year
	 * @param month
	 * @param date
	 * @return
	 */
	public static Calendar setCalendar(int year,int month,int date){
		Calendar cl = Calendar.getInstance();
		cl.set(year, month-1, date);
		return cl;
	}

	/**
	 * 獲取當前時間的前一天時間
	 * @param cl
	 * @return
	 */
	public static Calendar getBeforeDay(Calendar cl){
		//使用roll方法進行向前回滾
		//cl.roll(Calendar.DATE, -1);
		//使用set方法直接進行設定
		int day = cl.get(Calendar.DATE);
		cl.set(Calendar.DATE, day-1);
		return cl;
	}

	/**
	 * 獲取當前時間的後一天時間
	 * @param cl
	 * @return
	 */
	public  static Calendar getAfterDay(Calendar cl){
		//使用roll方法進行回滾到後一天的時間
		//cl.roll(Calendar.DATE, 1);
		//使用set方法直接設定時間值
		int day = cl.get(Calendar.DATE);
		cl.set(Calendar.DATE, day+1);
		return cl;
	}

	/**
	 * 列印時間
	 * @param cl
	 */
	public static void printCalendar(Calendar cl){
		int year = cl.get(Calendar.YEAR);
		int month = cl.get(Calendar.MONTH)+1;
		int day = cl.get(Calendar.DATE);
		System.out.println(year+"-"+month+"-"+day);
	}

	/**判斷時間是否在某個時間區間內**/
	public static boolean isInDates(String strDate, String strDateBegin,
			String strDateEnd) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date myDate = null;
		Date dateBegin = null;
		Date dateEnd = null;
		try {
			myDate = sd.parse(strDate);
			dateBegin = sd.parse(strDateBegin);
			dateEnd = sd.parse(strDateEnd);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		strDate = String.valueOf(myDate);
		strDateBegin = String.valueOf(dateBegin);
		strDateEnd = String.valueOf(dateEnd);

		int strDateH = Integer.parseInt(strDate.substring(11, 13));
		int strDateM = Integer.parseInt(strDate.substring(14, 16));
		int strDateS = Integer.parseInt(strDate.substring(17, 19));

		int strDateBeginH = Integer.parseInt(strDateBegin.substring(11, 13));
		int strDateBeginM = Integer.parseInt(strDateBegin.substring(14, 16));
		int strDateBeginS = Integer.parseInt(strDateBegin.substring(17, 19));

		int strDateEndH = Integer.parseInt(strDateEnd.substring(11, 13));
		int strDateEndM = Integer.parseInt(strDateEnd.substring(14, 16));
		int strDateEndS = Integer.parseInt(strDateEnd.substring(17, 19));

		if ((strDateH >= strDateBeginH && strDateH <= strDateEndH)) {
			if (strDateH > strDateBeginH && strDateH < strDateEndH) {
				return true;
			} else if (strDateH == strDateBeginH && strDateM > strDateBeginM
					&& strDateH < strDateEndH) {
				return true;
			} else if (strDateH == strDateBeginH && strDateM == strDateBeginM
					&& strDateS > strDateBeginS && strDateH < strDateEndH) {
				return true;
			} else if (strDateH == strDateBeginH && strDateM == strDateBeginM
					&& strDateS == strDateBeginS && strDateH < strDateEndH) {
				return true;
			} else if (strDateH > strDateBeginH && strDateH == strDateEndH
					&& strDateM < strDateEndM) {
				return true;
			} else if (strDateH > strDateBeginH && strDateH == strDateEndH
					&& strDateM == strDateEndM && strDateS < strDateEndS) {
				return true;
			} else if (strDateH > strDateBeginH && strDateH == strDateEndH
					&& strDateM == strDateEndM && strDateS == strDateEndS) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	/**判斷是否是今天**/
	public static boolean isToday(Date date) {
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		int year1 = c1.get(Calendar.YEAR);
		int month1 = c1.get(Calendar.MONTH) + 1;
		int day1 = c1.get(Calendar.DAY_OF_MONTH);
		Calendar c2 = Calendar.getInstance();
		c2.setTime(new Date());
		int year2 = c2.get(Calendar.YEAR);
		int month2 = c2.get(Calendar.MONTH) + 1;
		int day2 = c2.get(Calendar.DAY_OF_MONTH);
		if (year1 == year2 && month1 == month2 && day1 == day2) {
			return true;
		}
		return false;
	}

	/**
	 * 系統當前時間轉化為秒
	 * 
	 * @return
	 */
	public static long getUnixStamp() {
		return System.currentTimeMillis() / 1000;
	}

	/**
	 *
	 * 字串轉換為對應日期
	 *
	 * @param source
	 * @param pattern  "yyyy-MM-dd"
	 * @return
	 */
	public static Date stringToDate(String source, String pattern) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		Date date = null;
		try {
			date = simpleDateFormat.parse(source);
		} catch (Exception e) {
		}
		return date;
	}

	/**
	 * Date型別轉為指定格式的String型別
	 *
	 * @param source
	 * @param pattern
	 * @return
	 */
	public static String DateToString(Date source, String pattern) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		return simpleDateFormat.format(source);
	}

	/**
	 * 獲取前一天的時間的 年-月-日
	 * 
	 * @return
	 */
	public static String getYestoryDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String yestoday = sdf.format(calendar.getTime());
		return yestoday;
	}

	/**
	 * 獲取當前時間的 年-月-日
	 * 
	 * @return
	 */
	public static String getTodayDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new Date());
		return date;
	}

	/**
	 *  將當前時間秒的形式(1538129545)轉換為年月日-時分秒(2018-09-28 18:12:25)
	 * 
	 * @param timeStamp
	 * @return
	 */
	public static String timeStampToStr(long timeStamp) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(timeStamp * 1000);
		return date;
	}

	/**
	 * 將當前時間秒的形式(1538129545)轉換為年月日(2018-09-28)
	 * 
	 * @param timeStamp
	 *            ʱ���
	 * @return
	 */
	public static String formatDate(long timeStamp) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(timeStamp * 1000);
		return date;
	}

	/**
	 * 當前時間秒的形式轉化為 HH:mm:ss
	 * 
	 * @param timeStamp
	 *            ʱ���
	 * @return
	 */
	public static String getTime(long timeStamp) {
		String time = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(timeStamp * 1000);
		String[] split = date.split("\\s");
		if (split.length > 1) {
			time = split[1];
		}
		return time;
	}

	/**
	 * 判斷目標日期距離當前日期多長時間
	 * 
	 * @param timeStamp
	 * @return
	 */
	public static String convertTimeToFormat(long timeStamp) {
		long curTime = System.currentTimeMillis() / (long) 1000;
		long time = curTime - timeStamp;

		if (time < 60 && time >= 0) {
			return "剛剛";
		} else if (time >= 60 && time < 3600) {
			return time / 60 + "分鐘";
		} else if (time >= 3600 && time < 3600 * 24) {
			return time / 3600 + "小時";
		} else if (time >= 3600 * 24 && time < 3600 * 24 * 30) {
			return time / 3600 / 24 + "天";
		} else if (time >= 3600 * 24 * 30 && time < 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 + "月";
		} else if (time >= 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 / 12 + "年";
		} else {
			return "剛剛";
		}
	}

	/**
	 *計算當前實際愛你和系統時間相差幾秒
	 * 
	 * @param timeStamp
	 * @return
	 */
	public static String timeStampToFormat(long timeStamp) {
		long curTime = System.currentTimeMillis() / (long) 1000;
		long time = curTime - timeStamp;
		return time / 60 + "";
	}

	/** 獲取當天中午12點的時間(毫秒) **/
	public static Long getStartTime() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		return todayStart.getTime().getTime();
	}

	/**獲取下一天中午12點的時間(毫秒)**/
	public static Long getEndTime() {
		Calendar todayEnd = Calendar.getInstance();
		todayEnd.set(Calendar.HOUR, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		todayEnd.set(Calendar.MILLISECOND, 999);
		return todayEnd.getTime().getTime();
	}

	// 呼叫這個方法 你傳入一個日期 就能獲得 這個日期所在一週內的所有天數的一個List
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static List<Date> dateToWeek(Date mdate) {
		// System.out.println("mdate :" + mdate);
		int b = mdate.getDay();
		// System.out.println("b:  " + b);
		Date fdate;
		List<Date> list = new ArrayList();
		Long fTime = mdate.getTime() - b * 24 * 3600000;
		// System.out.println("fTime: " + fTime);
		for (int a = 0; a < 8; a++) {
			fdate = new Date();
			fdate.setTime(fTime + (a * 24 * 3600000));
			list.add(a, fdate);
		}

		return list;
	}

	/**
	 * 根據日期獲得所在周的日期
	 * 
	 * @param mdate
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static List<Date> dateOfWeek(Date mdate) {
		int b = mdate.getDay();
		Date fdate;
		List<Date> list = new ArrayList<Date>();
		Long fTime = mdate.getTime() - b * 24 * 3600000;
		for (int a = 1; a <= 7; a++) {
			fdate = new Date();
			fdate.setTime(fTime + (a * 24 * 3600000));
			list.add(a - 1, fdate);
		}
		return list;
	}

	/**
	 * 把毫秒轉化成日期
	 * 
	 * @param dateFormat
	 *            (日期格式,例如:MM/ dd/yyyy HH:mm:ss)
	 * @param millSec
	 *            (毫秒數)
	 * @return
	 */
	private static String transferLongToDate(String dateFormat, Long millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = new Date(millSec);
		return sdf.format(date);
	}

	// 獲取當天的開始時間
	public static Date getDayBegin() {
		Calendar cal = new GregorianCalendar();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}

	// 獲取當天的結束時間
	public static Date getDayEnd() {
		Calendar cal = new GregorianCalendar();
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		return cal.getTime();
	}

	// 獲取昨天的開始時間
	public static Date getBeginDayOfYesterday() {
		Calendar cal = new GregorianCalendar();
		cal.setTime(getDayBegin());
		cal.add(Calendar.DAY_OF_MONTH, -1);
		return cal.getTime();
	}

	// 獲取昨天的結束時間
	public static Date getEndDayOfYesterDay() {
		Calendar cal = new GregorianCalendar();
		cal.setTime(getDayEnd());
		cal.add(Calendar.DAY_OF_MONTH, -1);
		return cal.getTime();
	}

	// 獲取明天的開始時間
	public static Date getBeginDayOfTomorrow() {
		Calendar cal = new GregorianCalendar();
		cal.setTime(getDayBegin());
		cal.add(Calendar.DAY_OF_MONTH, 1);

		return cal.getTime();
	}

	// 獲取明天的結束時間
	public static Date getEndDayOfTomorrow() {
		Calendar cal = new GregorianCalendar();
		cal.setTime(getDayEnd());
		cal.add(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}

	// 獲取本週的開始時間
	public static Date getBeginDayOfWeek() {
		Date date = new Date();
		if (date == null) {
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
		if (dayofweek == 1) {
			dayofweek += 7;
		}
		cal.add(Calendar.DATE, 2 - dayofweek);
		return getDayStartTime(cal.getTime());
	}

	// 獲取本週的結束時間
	public static Date getEndDayOfWeek() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getBeginDayOfWeek());
		cal.add(Calendar.DAY_OF_WEEK, 6);
		Date weekEndSta = cal.getTime();
		return getDayEndTime(weekEndSta);
	}

	// 獲取本月的開始時間
	public static Date getBeginDayOfMonth() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(getNowYear(), getNowMonth() - 1, 1);
		return getDayStartTime(calendar.getTime());
	}

	// 獲取本月的結束時間
	public static Date getEndDayOfMonth() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(getNowYear(), getNowMonth() - 1, 1);
		int day = calendar.getActualMaximum(5);
		calendar.set(getNowYear(), getNowMonth() - 1, day);
		return getDayEndTime(calendar.getTime());
	}

	// 獲取本年的開始時間
	public static Date getBeginDayOfYear() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, getNowYear());
		// cal.set
		cal.set(Calendar.MONTH, Calendar.JANUARY);
		cal.set(Calendar.DATE, 1);

		return getDayStartTime(cal.getTime());
	}

	// 獲取本年的結束時間
	public static Date getEndDayOfYear() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, getNowYear());
		cal.set(Calendar.MONTH, Calendar.DECEMBER);
		cal.set(Calendar.DATE, 31);
		return getDayEndTime(cal.getTime());
	}

	// 獲取某個日期的開始時間
	public static Timestamp getDayStartTime(Date d) {
		Calendar calendar = Calendar.getInstance();
		if (null != d)
			calendar.setTime(d);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return new Timestamp(calendar.getTimeInMillis());
	}

	// 獲取某個日期的結束時間
	public static Timestamp getDayEndTime(Date d) {
		Calendar calendar = Calendar.getInstance();
		if (null != d)
			calendar.setTime(d);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return new Timestamp(calendar.getTimeInMillis());
	}

	// 獲取今年是哪一年
	public static Integer getNowYear() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return Integer.valueOf(gc.get(1));
	}

	// 獲取本月是哪一月
	public static int getNowMonth() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return gc.get(2) + 1;
	}

	// 兩個日期相減得到的天數
	public static int getDiffDays(Date beginDate, Date endDate) {

		if (beginDate == null || endDate == null) {
			throw new IllegalArgumentException("getDiffDays param is null!");
		}

		long diff = (endDate.getTime() - beginDate.getTime())
				/ (1000 * 60 * 60 * 24);

		int days = new Long(diff).intValue();

		return days;
	}

	// 兩個日期相減得到的毫秒數
	public static long dateDiff(Date beginDate, Date endDate) {
		long date1ms = beginDate.getTime();
		long date2ms = endDate.getTime();
		return date2ms - date1ms;
	}

	// 獲取兩個日期中的最大日期
	public static Date max(Date beginDate, Date endDate) {
		if (beginDate == null) {
			return endDate;
		}
		if (endDate == null) {
			return beginDate;
		}
		if (beginDate.after(endDate)) {
			return beginDate;
		}
		return endDate;
	}

	// 獲取兩個日期中的最小日期
	public static Date min(Date beginDate, Date endDate) {
		if (beginDate == null) {
			return endDate;
		}
		if (endDate == null) {
			return beginDate;
		}
		if (beginDate.after(endDate)) {
			return endDate;
		}
		return beginDate;
	}

	// 返回某月該季度的第一個月
	public static Date getFirstSeasonDate(Date date) {
		final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int sean = SEASON[cal.get(Calendar.MONTH)];
		cal.set(Calendar.MONTH, sean * 3 - 3);
		return cal.getTime();
	}

	// 返回某個日期下幾天的日期
	public static Date getNextDay(Date date, int i) {
		Calendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
		return cal.getTime();
	}

	// 返回某個日期前幾天的日期
	public static Date getFrontDay(Date date, int i) {
		Calendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
		return cal.getTime();
	}

	// 獲取某年某月到某年某月按天的切片日期集合(間隔天數的集合)
	public static List getTimeList(int beginYear, int beginMonth, int endYear,
			int endMonth, int k) {
		List list = new ArrayList();
		if (beginYear == endYear) {
			for (int j = beginMonth; j <= endMonth; j++) {
				list.add(getTimeList(beginYear, j, k));

			}
		} else {
			{
				for (int j = beginMonth; j < 12; j++) {
					list.add(getTimeList(beginYear, j, k));
				}

				for (int i = beginYear + 1; i < endYear; i++) {
					for (int j = 0; j < 12; j++) {
						list.add(getTimeList(i, j, k));
					}
				}
				for (int j = 0; j <= endMonth; j++) {
					list.add(getTimeList(endYear, j, k));
				}
			}
		}
		return list;
	}

	// 獲取某年某月按天切片日期集合(某個月間隔多少天的日期集合)
	public static List getTimeList(int beginYear, int beginMonth, int k) {
		List list = new ArrayList();
		Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
		int max = begincal.getActualMaximum(Calendar.DATE);
		for (int i = 1; i < max; i = i + k) {
			list.add(begincal.getTime());
			begincal.add(Calendar.DATE, k);
		}
		begincal = new GregorianCalendar(beginYear, beginMonth, max);
		list.add(begincal.getTime());
		return list;
	}
}