1. 程式人生 > >Java Date時間的處理-Date工具類

Java Date時間的處理-Date工具類

package tag;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

 
/**
 * 取得標準格式日期和時間
 * @author zhaojunchang
 *
 */
public class DateFormat {

	/** 預設日期格式 */
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

	/** 預設時間格式 */
	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

	/** 預設月格式 */
	public static final String DEFAULT_MONTH = "MONTH";

	/** 預設年格式 */
	public static final String DEFAULT_YEAR = "YEAR";

	/** 預設日格式 */
	public static final String DEFAULT_DATE = "DAY";

	/** 預設小時格式 */
	public static final String DEFAULT_HOUR = "HOUR";

	/** 預設分鐘格式 */
	public static final String DEFAULT_MINUTE = "MINUTE";

	/** 預設秒格式 */
	public static final String DEFAULT_SECOND = "SECOND";

	/** 預設長日期格式 */
	public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH-mm";

	/** 預設長日期格式,精確到秒 */
	public static final String DEFAULT_DATETIME_FORMAT_SEC = "yyyy-MM-dd HH:mm:ss";

	/** 星期陣列 */
	public static final String[] WEEKS = { "星期日", "星期一", "星期二", "星期三", "星期四",
			"星期五", "星期六" };

	/**
	 * 取當前日期的字串表示
	 * 
	 * @return 當前日期的字串 ,如2010-05-28
	 **/
	public static String today() {
		return today(DEFAULT_DATE_FORMAT);
	}

	/**
	 * 根據輸入的格式得到當前日期的字串
	 * 
	 * @param strFormat
	 *            日期格式
	 * @return
	 */
	public static String today(String strFormat) {
		return toString(new Date(), strFormat);
	}

	/**
	 * 取當前時間的字串表示,
	 * 
	 * @return 當前時間,如:21:10:12
	 **/
	public static String currentTime() {
		return currentTime(DEFAULT_TIME_FORMAT);
	}

	/**
	 * 根據輸入的格式獲取時間的字串表示 'hh:mm:ss'
	 * 
	 * @return 當前時間,如:21:10:12
	 **/

	public static String currentTime(String strFormat) {
		return toString(new Date(), strFormat);
	}

	/**
	 * 取得相對於當前時間增加天數/月數/年數後的日期 <br>
	 * 欲取得當前日期5天前的日期,可做如下呼叫:<br>
	 * getAddDay("DATE", -5).
	 * 
	 * @param field
	 *            ,段,如"year","month","date",對大小寫不敏感
	 * @param amount
	 *            ,增加的數量(減少用負數表示),如5,-1
	 * @return 格式化後的字串 如"2010-05-28"
	 * @throws ParseException
	 **/

	public static String getAddDay(String field, int amount)
			throws ParseException {
		return getAddDay(field, amount, null);
	}

	/**
	 * 取得相對於當前時間增加天數/月數/年數後的日期,按指定格式輸出
	 * 
	 * 欲取得當前日期5天前的日期,可做如下呼叫:<br>
	 * getAddDay("DATE", -5,'yyyy-mm-dd hh:mm').
	 * 
	 * @param field
	 *            ,段,如"year","month","date",對大小寫不敏感
	 * @param amount
	 *            ,增加的數量(減少用負數表示),如5,-1
	 * @param strFormat
	 *            ,輸出格式,如"yyyy-mm-dd","yyyy-mm-dd hh:mm"
	 * @return 格式化後的字串 如"2010-05-28"
	 * @throws ParseException
	 **/
	public static String getAddDay(String field, int amount, String strFormat)
			throws ParseException {
		return getAddDay(null, field, amount, strFormat);
	}

	/**
	 * 功能:對於給定的時間增加天數/月數/年數後的日期,按指定格式輸出
	 * 
	 * @param date
	 *            String 要改變的日期
	 * @param field
	 *            int 日期改變的欄位,YEAR,MONTH,DAY
	 * @param amount
	 *            int 改變數
	 * @param strFormat
	 *            日期返回格式
	 * @return
	 * @throws ParseException
	 */
	public static String getAddDay(String date, String field, int amount,
			String strFormat) throws ParseException {
		if (strFormat == null) {
			strFormat = DEFAULT_DATETIME_FORMAT_SEC;
		}
		Calendar rightNow = Calendar.getInstance();
		if (date != null && !"".equals(date.trim())) {
			rightNow.setTime(parseDate(date, strFormat));
		}
		if (field == null) {
			return toString(rightNow.getTime(), strFormat);
		}
		rightNow.add(getInterval(field), amount);
		return toString(rightNow.getTime(), strFormat);
	}

	/**
	 * 獲取時間間隔型別
	 * 
	 * @param field
	 *            時間間隔型別
	 * @return 日曆的時間間隔
	 */
	protected static int getInterval(String field) {
		String tmpField = field.toUpperCase();
		if (tmpField.equals(DEFAULT_YEAR)) {
			return Calendar.YEAR;
		} else if (tmpField.equals(DEFAULT_MONTH)) {
			return Calendar.MONTH;
		} else if (tmpField.equals(DEFAULT_DATE)) {
			return Calendar.DATE;
		} else if (DEFAULT_HOUR.equals(tmpField)) {
			return Calendar.HOUR;
		} else if (DEFAULT_MINUTE.equals(tmpField)) {
			return Calendar.MINUTE;
		} else {
			return Calendar.SECOND;
		}
	}

	/**
	 * 獲取格式化物件
	 * 
	 * @param strFormat
	 *            格式化的格式 如"yyyy-MM-dd"
	 * @return 格式化物件
	 */
	public static SimpleDateFormat getSimpleDateFormat(String strFormat) {
		if (strFormat != null && !"".equals(strFormat.trim())) {
			return new SimpleDateFormat(strFormat);
		} else {
			return new SimpleDateFormat();
		}
	}

	/**
	 * 得到當前日期的星期數
	 * 
	 * @return 當前日期的星期的字串
	 * @throws ParseException
	 */
	public static String getWeekOfMonth() throws ParseException {
		return getWeekOfMonth(null, null);
	}

	/**
	 * 根據日期的到給定日期的在當月中的星期數
	 * 
	 * @param date
	 *            給定日期
	 * @return
	 * @throws ParseException
	 */
	public static String getWeekOfMonth(String date, String fromat)
			throws ParseException {
		Calendar rightNow = Calendar.getInstance();
		if (date != null && !"".equals(date.trim())) {
			rightNow.setTime(parseDate(date, fromat));
		}
		return WEEKS[rightNow.get(Calendar.WEEK_OF_MONTH)];
	}

	/**
	 * 將java.util.date型按照指定格式轉為字串
	 * 
	 * @param date
	 *            源物件
	 * @param format
	 *            想得到的格式字串
	 * @return 如:2010-05-28
	 */
	public static String toString(Date date, String format) {
		return getSimpleDateFormat(format).format(date);
	}

	/**
	 * 將java.util.date型按照預設格式轉為字串
	 * 
	 * @param date
	 *            源物件
	 * @return 如:2010-05-28
	 */
	public static String toString(Date date) {
		return toString(date, DEFAULT_DATE_FORMAT);
	}

	/**
	 * 強制型別轉換 從串到日期
	 * 
	 * @param sDate
	 *            源字串,採用yyyy-MM-dd格式
	 * @param sFormat
	 *            ps
	 * @return 得到的日期物件
	 * @throws ParseException
	 */
	public static Date parseDate(String strDate, String format)
			throws ParseException {
		return getSimpleDateFormat(format).parse(strDate);
	}

	/***
	 * 根據傳入的毫秒數和格式,對日期進行格式化輸出
	 * 
	 * @version 2011-7-12
	 * @param object
	 * @param format
	 * @return
	 */
	public static String millisecondFormat(Long millisecond, String format) {
		if (millisecond == null || millisecond <= 0) {
			throw new IllegalArgumentException(String.format("傳入的時間毫秒數[%s]不合法",
					"" + millisecond));
		}
		if (format == null || "".equals(format.trim())) {
			format = DEFAULT_DATE_FORMAT;
		}
		return toString(new Date(millisecond), format);
	}

	/**
	 * 強制型別轉換 從串到時間戳
	 * 
	 * @param sDate
	 *            源串
	 * @param sFormat
	 *            遵循格式
	 * @return 取得的時間戳物件
	 * @throws ParseException
	 */
	public static Timestamp parseTimestamp(String strDate, String format)
			throws ParseException {
		Date utildate = getSimpleDateFormat(format).parse(strDate);
		return new Timestamp(utildate.getTime());
	}

	/**
	 * getCurDate 取當前日期
	 * 
	 * @return java.util.Date型日期
	 **/
	public static Date getCurDate() {
		return (new Date());
	}

	/**
	 * getCurTimestamp 取當前時間戳
	 * 
	 * @return java.sql.Timestamp
	 **/
	public static Timestamp getCurTimestamp() {
		return new Timestamp(new Date().getTime());
	}

	/**
	 * getCurTimestamp 取遵循格式的當前時間
	 * 
	 * @param sFormat
	 *            遵循格式
	 * @return java.sql.Timestamp
	 **/
	public static Date getCurDate(String format) throws Exception {
		return getSimpleDateFormat(format).parse(toString(new Date(), format));
	}

	/**
	 * Timestamp按照指定格式轉為字串
	 * 
	 * @param timestamp
	 *            源物件
	 * @param format
	 *            ps(如yyyy.mm.dd)
	 * @return 如:2010-05-28 或2010-05-281 13:21
	 */
	public static String toString(Timestamp timestamp, String format) {
		if (timestamp == null) {
			return "";
		}
		return toString(new Date(timestamp.getTime()), format);
	}

	/**
	 * Timestamp按照預設格式轉為字串
	 * 
	 * @param ts
	 *            源物件
	 * @return 如:2010-05-28
	 */
	public static String toString(Timestamp ts) {
		return toString(ts, DEFAULT_DATE_FORMAT);
	}

	/**
	 * Timestamp按照預設格式轉為字串,可指定是否使用長格式
	 * 
	 * @param timestamp
	 *            欲轉化之變數Timestamp
	 * @param fullFormat
	 *            是否使用長格式
	 * @return 如:2010-05-28 或2010-05-28 21:21
	 */
	public static String toString(Timestamp timestamp, boolean fullFormat) {
		if (fullFormat) {
			return toString(timestamp, DEFAULT_DATETIME_FORMAT_SEC);
		} else {
			return toString(timestamp, DEFAULT_DATE_FORMAT);
		}
	}

	/**
	 * 將sqldate型按照指定格式轉為字串
	 * 
	 * @param sqldate
	 *            源物件
	 * @param sFormat
	 *            ps
	 * @return 如:2010-05-28 或2010-05-28 00:00
	 */
	public static String toString(java.sql.Date sqldate, String sFormat) {
		if (sqldate == null) {
			return "";
		}
		return toString(new Date(sqldate.getTime()), sFormat);
	}

	/**
	 * 將sqldate型按照預設格式轉為字串
	 * 
	 * @param sqldate
	 *            源物件
	 * @return 如:2010-05-28
	 */
	public static String toString(java.sql.Date sqldate) {
		return toString(sqldate, DEFAULT_DATE_FORMAT);
	}

	/**
	 * 計算日期時間之間的差值, date1得時間必須大於date2的時間
	 * 
	 * @version 2011-7-12
	 * @param date1
	 * @param date2
	 * @return {@link java.util.Map} Map的鍵分別為, day(天),
	 *         hour(小時),minute(分鐘)和second(秒)。
	 */
	public static Map<String, Long> timeDifference(final Date date1,
			final Date date2) {
		if (date1 == null || date2 == null) {
			throw new NullPointerException("date1 and date2 can't null");
		}
		long mim1 = date1.getTime();
		long mim2 = date2.getTime();
		if (mim1 < mim2) {
			throw new IllegalArgumentException(String.format(
					"date1[%s] not be less than date2[%s].", mim1 + "", mim2
							+ ""));
		}
		long m = (mim1 - mim2 + 1) / 1000l;
		long mday = 24 * 3600;
		final Map<String, Long> map = new HashMap<String, Long>();
		map.put("day", m / mday);
		m = m % mday;
		map.put("hour", (m) / 3600);
		map.put("minute", (m % 3600) / 60);
		map.put("second", (m % 3600 % 60));
		return map;
	}

	public static Map<String, Integer> compareTo(final Date date1,
			final Date date2) {
		if (date1 == null || date2 == null) {
			return null;
		}
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		long time = Math.max(time1, time2) - Math.min(time1, time2);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(time);
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("year", (calendar.get(Calendar.YEAR) - 1970) > 0 ? (calendar
				.get(Calendar.YEAR) - 1970) : 0);
		map.put("month", (calendar.get(Calendar.MONTH) - 1) > 0 ? (calendar
				.get(Calendar.MONTH) - 1) : 0);
		map.put("day",
				(calendar.get(Calendar.DAY_OF_MONTH) - 1) > 0 ? (calendar
						.get(Calendar.DAY_OF_MONTH) - 1) : 0);
		map.put("hour",
				(calendar.get(Calendar.HOUR_OF_DAY) - 8) > 0 ? (calendar
						.get(Calendar.HOUR_OF_DAY) - 8) : 0);
		map.put("minute", calendar.get(Calendar.MINUTE) > 0 ? calendar
				.get(Calendar.MINUTE) : 0);
		map.put("second", calendar.get(Calendar.SECOND) > 0 ? calendar
				.get(Calendar.SECOND) : 0);
		return map;
	}

	public static void main(String[] args) {
		System.out.println(today());
	}
}