1. 程式人生 > >java日期處理簡單封裝

java日期處理簡單封裝

今天沒什麼事情做,溫習一下基本知識,在網上看到和日期處理的相關框架,什麼joda,date4j等,都宣稱超級強大簡單易用。下下來試了下,確實都挺不錯。不過自己不是經常涉及到日期操作,且涉及到的也不復雜。且不說這些庫的功能強不強大,單說為了處理個時間就引入幾十個類,實在有點浪費了。再說JDK提供的Calendar和SimpleDateFormat組合使用功能也還是非常強大啊。如果覺得同時使用這兩個類稍顯麻煩,可以稍微封裝一下,即可滿足大部分需求,就一個類,自己需要用到什麼功能的時候,新增進去就行了。

package luojing.date;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 日期時間處理封裝
 * 
 * @author luojing
 */
public class DateTime implements Comparable<DateTime>, Serializable {

	private static final long serialVersionUID = 4715414577633839197L;
	private Calendar calendar = Calendar.getInstance();
	private SimpleDateFormat sdf = new SimpleDateFormat();

	private final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	private final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
	private final String DEFAULT_TIME_PATTERN = "HH:mm:ss";

	public DateTime() {
	}

	public DateTime(String dateStr) {
		try {
			parse(dateStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public DateTime(String dateStr, TimeZone timeZone) {
		this(dateStr);
		calendar.setTimeZone(timeZone);
	}

	public DateTime(String dateStr, String pattern) {
		try {
			parse(dateStr, pattern);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public DateTime(String dateStr, String pattern, TimeZone timeZone) {
		this(dateStr, pattern);
		calendar.setTimeZone(timeZone);
	}

	public DateTime(int year, int month, int day, int hour, int minute, int second) {
		calendar.set(year, month, day, hour, minute, second);
	}

	public DateTime(int year, int month, int day, int hour, int minute, int second, TimeZone timeZone) {
		this(year, month, day, hour, minute, second);
		calendar.setTimeZone(timeZone);
	}

	public DateTime(long milliSeconds) {
		calendar.setTimeInMillis(milliSeconds);
	}

	public Calendar getCalendar() {
		return calendar;
	}

	public void setCalendar(Calendar calendar) {
		this.calendar = calendar;
	}

	public Date getDate() {
		return calendar.getTime();
	}

	public void setDate(Date date) {
		calendar.setTime(date);
	}

	public int getYear() {
		return calendar.get(Calendar.YEAR);
	}

	public void setYear(int year) {
		calendar.set(Calendar.YEAR, year);
	}

	public int getMonth() {
		return calendar.get(Calendar.MONTH);
	}

	public void setMonth(int month) {
		calendar.set(Calendar.MONTH, month);
	}

	public int getDay() {
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	public void setDay(int dayOfMonth) {
		calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	}

	public int getHour() {
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	public void setHour(int hour) {
		calendar.set(Calendar.HOUR_OF_DAY, hour);
	}

	public int getMinute() {
		return calendar.get(Calendar.MINUTE);
	}

	public void setMinute(int minute) {
		calendar.set(Calendar.MINUTE, minute);
	}

	public int getSecond() {
		return calendar.get(Calendar.SECOND);
	}

	public void setSecond(int second) {
		calendar.set(Calendar.SECOND, second);
	}

	public long getTimeInMilliSeconds() {
		return calendar.getTimeInMillis();
	}

	public void setTimeInMilliSeconds(long milliSeconds) {
		calendar.setTimeInMillis(milliSeconds);
	}

	public TimeZone getTimeZone() {
		return calendar.getTimeZone();
	}

	public void setTimeZone(TimeZone timeZone) {
		calendar.setTimeZone(timeZone);
	}

	/**
	 * 使用預設格式解析日期字串
	 * 
	 * @param dateStr
	 * @throws Exception
	 */
	public void parse(String dateStr) throws Exception {
		try {
			parse(dateStr, DEFAULT_DATETIME_PATTERN);
		} catch (Exception e) {
			try {
				parse(dateStr, DEFAULT_DATE_PATTERN);
			} catch (Exception e1) {
				try {
					parse(dateStr, DEFAULT_TIME_PATTERN);
				} catch (Exception e2) {
					throw new Exception("the date string [" + dateStr + "] could not be parsed");
				}
			}
		}

	}

	/**
	 * 使用給定模式解析日期字串
	 * 
	 * @param dateStr
	 * @param pattern
	 * @throws Exception
	 */
	public void parse(String dateStr, String pattern) throws Exception {
		if (dateStr == null) {
			throw new NullPointerException("date string could not be null");
		}

		if (pattern == null) {
			throw new NullPointerException("the pattern string could not be null");
		}

		try {
			sdf.applyPattern(pattern);
			sdf.parse(dateStr);
		} catch (ParseException e) {
			throw new Exception("the date string [" + dateStr + "] could not be parsed with the pattern [" + pattern + "]");
		}
		calendar = sdf.getCalendar();
	}

	/**
	 * 格式化當前DateTime物件代表的時間
	 * 
	 * @param pattern
	 * @return
	 */
	public String format(String pattern) {
		sdf.applyPattern(pattern);
		return sdf.format(calendar.getTime());
	}

	/**
	 * 獲取預設格式日期字串
	 * 
	 * @return
	 */
	public String toDateTimeString() {
		sdf.applyPattern(DEFAULT_DATETIME_PATTERN);
		return sdf.format(calendar.getTime());
	}

	@Override
	public int compareTo(DateTime otherDateTime) {
		return calendar.compareTo(otherDateTime.getCalendar());
	}

	/**
	 * 是否閏年
	 * 
	 * @return
	 */
	public boolean isLeapYear() {
		int year = getYear();
		boolean result = false;
		if (year % 100 == 0) {
			if (year % 400 == 0) {
				result = true;
			}
		} else if (year % 4 == 0) {
			result = true;
		}
		return result;
	}

	/**
	 * 獲取星期
	 * 
	 * @return
	 */
	public int getDayOfWeek() {
		return calendar.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * 是否週末
	 * 
	 * @return
	 */
	public boolean isWeekend() {
		int dayOfWeek = getDayOfWeek();
		return dayOfWeek == 1 || dayOfWeek == 7;
	}

	/**
	 * 當前DateTime物件月份天數
	 * 
	 * @return
	 */
	public int getDayNumsInMonth() {
		Calendar c = (Calendar) calendar.clone();
		c.set(Calendar.DAY_OF_MONTH, 1);
		c.roll(Calendar.DAY_OF_MONTH, -1);
		return c.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 兩個日期之間間隔天數
	 * 
	 * @param otherDateTime
	 * @return
	 */
	public int dayNumFrom(DateTime otherDateTime) {
		long millis = Math.abs(getTimeInMilliSeconds() - otherDateTime.getTimeInMilliSeconds());
		int days = (int) Math.floor(millis / 86400000);
		return days;
	}

	public boolean lessThan(DateTime otherDateTime) {
		return compareTo(otherDateTime) < 0;
	}

	public boolean greaterThan(DateTime otherDateTime) {
		return compareTo(otherDateTime) > 0;
	}

	public boolean equal(DateTime otherDateTime) {
		return compareTo(otherDateTime) == 0;
	}

	/**
	 * 當前時間基礎上增加秒數(負數時為減)
	 * 
	 * @param amount
	 */
	public void plusSecond(int amount) {
		calendar.add(Calendar.SECOND, amount);
	}

	public void plusMinute(int amount) {
		calendar.add(Calendar.MINUTE, amount);
	}

	public void plusHour(int amount) {
		calendar.add(Calendar.HOUR, amount);
	}

	public void plusDays(int amount) {
		calendar.add(Calendar.DAY_OF_MONTH, amount);
	}

	public void plusMonth(int amount) {
		calendar.add(Calendar.MONTH, amount);
	}

	public void plusYear(int amount) {
		calendar.add(Calendar.YEAR, amount);
	}

	public void plus(int year, int month, int day, int hour, int minute, int second) {
		plusYear(year);
		plusMonth(month);
		plusDays(day);
		plusHour(hour);
		plusMinute(minute);
		plusSecond(second);
	}

}
測試:
package luojing.date;

import java.util.Date;

public class DateTimeTest {

	public static void main(String[] args) throws Exception {
		DateTime dateTime = new DateTime();
		DateTime dateTime2 = new DateTime("2013-12-12");
		System.out.println("預設格式輸出:" + dateTime.toDateTimeString());
		System.out.println("是否閏年:" + dateTime.isLeapYear());
		System.out.println("自定義格式輸出:" + dateTime.format("yyyy-MM-dd"));
		System.out.println("輸出到毫秒:" + dateTime.format("yyyy-MM-dd HH:mm:ss.SSS"));
		System.out.println("某月天數:" + dateTime.getDayNumsInMonth());
		System.out.println("星期:" + dateTime.getDayOfWeek());//1:星期日,7:星期六
		System.out.println("是否週末:" + dateTime.isWeekend());
		System.out.println("相距:" + dateTime.dayNumFrom(dateTime2) + "天");
		
		dateTime.plusMonth(1);
		System.out.println("增加一個月後的datetime: " + dateTime.toDateTimeString());
		dateTime.plus(0, 0, 2, 4, 4, 5);
		System.out.println("增加 XXX後的datetime: " + dateTime.toDateTimeString());
		System.out.println("毫秒數:" + dateTime.getTimeInMilliSeconds());
		
		//DateTime轉換為Date
		Date date = dateTime.getDate();
		System.out.println( dateTime.getTimeInMilliSeconds() == date.getTime());
	}
}

輸出:

預設格式輸出:2013-09-25 19:16:15
是否閏年:false
自定義格式輸出:2013-09-25
輸出到毫秒:2013-09-25 19:16:15.278
某月天數:30
星期:4
是否週末:false
相距:77天
增加一個月後的datetime: 2013-10-25 19:16:15
增加 XXX後的datetime: 2013-10-27 23:20:20
毫秒數:1382887220278
true

本人使用到日期處理相關的操作,大多就是格式化時間和時間之間的比較。這個封裝已經完全能夠滿足我的日常需要了,再說,即使找不到合適的封裝方法,還可以直接獲取包裝的calendar物件來做處理。

相關推薦

java日期處理簡單封裝

今天沒什麼事情做,溫習一下基本知識,在網上看到和日期處理的相關框架,什麼joda,date4j等,都宣稱超級強大簡單易用。下下來試了下,確實都挺不錯。不過自己不是經常涉及到日期操作,且涉及到的也不復雜。且不說這些庫的功能強不強大,單說為了處理個時間就引入幾十個類,實在有點浪

java日期處理 java日期處理總結

轉載:https://www.cnblogs.com/lcngu/p/5154834.html   java日期處理總結   Java日期時間使用總結   一、Java中的日期概述 &

java 日期處理工具類

package com.conb.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.

java 日期處理工具類 DateUtil

http://bjtdeyx.iteye.com/blog/1551946 Java 日期時間 Date型別,long型別,String型別表現形式的轉換 http://www.xuebuyuan.com/1756921.html

Java基於apache.commons.lang的日期工具類簡單封裝

package cn.lettleprincess.util; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util

java 接口自動化測試之數據請求的簡單封裝

public 事業 交互界面 參數 lencod name route cli asi 我們自己用java寫接口自動化測試框架或者做個接口自動化測試平臺的話,是需要自己進行相關的請求的,因此我們需要簡單的封裝下httpclient,我新建了一個http工具類,將

Java的幾個有用小Util函數(日期處理和http)

content lex .get get sta mmd 第幾天 service ret /** * 依據日期返回當前日期是一年的第幾天 * @param date * @return */ public stat

Java之異常處理日期處理

出了 指定 初始化 ring () next height 常見問題 自定義 Java異常處理 異常:異常就是Java程序在運行過程中出現的錯誤。 異常由來:問題也是現實生活中一個具體事務,也可以通過java 的類的形式進行描述,並封裝成對象。其實就是Java對不正常情

java工具包一:日期處理

div 方便 開始 .text simple nor atd blog param 作者:NiceCui 本文謝絕轉載,如需轉載需征得作者本人同意,謝謝。 本文鏈接:http://www.cnblogs.com/NiceCui/p/7846812.html 郵箱:

關於java和javascript互動中的日期處理問題彙總

javascript部分 分兩種情況: —-後臺接收long型 ——–js處理 (new Date()).getTime()//Date轉long,預設new Date()可以把當前日期時間精確到秒 輸出結果:1455862677881//即2016/2/19 14:17:5

java時間日期處理

創作不易,請勿抄襲,轉載請註明出處。如有疑問,請加微信 wx15151889890,謝謝。 [本文連結:]https://blog.csdn.net/wx740851326/article/details/https://blog.csdn.net/wx740851326/article

Java日期格式以及生成相應日期-封裝呼叫

package com.yihuisoft.common.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; impor

Java日期和字串之間轉換,自己封裝日期與字串轉換類

一:日期與字串轉換 public class DateFormatDemo { public static void main(String[] args) throws ParseException { //日期轉換成字串 Date d = new Date(); Simple

Java學習——private實現封裝處理

Java封裝處理(private封裝) 所謂封裝,也就是把客觀事物封裝成抽象的類,並且類可以把自己的資料和方法只讓可信的類或者物件操作,對不可信的進行資訊隱藏。簡而言之就是,內部操作對外部而言不可見(保護性) 。 封裝是面向物件裡最複雜的概念,使用private關鍵字實現

Python:以字典的形式處理CSV簡單封裝

#!/usr/bin/env python # coding:UTF-8 """ @version: python3.x @author:曹新健 @contact: [email protected] @software: PyCharm @file: CSV簡

Android6.0執行時許可權處理-超簡單封裝

之前除錯的時候,出現了一個問題,就是當我開啟二維碼掃描介面的時候,對於一部分手機一直不會出現那個掃描框,這點我也很是鬱悶,這不好整啊,畢竟二維碼介面是用的別人的,怎麼改啊?這個時候我分析了一下原因,最後知道只有部分6.0的手機才會出現這種情況,那麼這就簡單了。下

簡單封裝Jackson,實現JSON String到Java Object的Mapper.

import java.io.IOException; import java.util.Collection; import java.util.Map; import org.apache.commons.lang3.StringUtils; imp

Java中的時間日期處理

日常開發中對時間或者日期處理肯定層出不窮,簡單總結一下Java中時間相關的使用方法。 相關類 Date: Date表示特定的瞬間,精確到毫秒,Date中的相應方法已廢棄,從JDK 1.1開

Java系統中時間封裝處理

package com.cloud.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import

JS 獲取前七天時間以及日期簡單處理

獲取日期時間         //當天         var Date1 = new Date();         //前一天         var Date2 = new Date(Date1.getTime() - 24*60*60*1000);