首頁  >  文章  >  类库下载  >  使用apache.lang套件安全簡潔地操作Java時間

使用apache.lang套件安全簡潔地操作Java時間

高洛峰
高洛峰原創
2016-10-15 17:34:581796瀏覽

在這之前還是先簡單說一下java本身的時間處理類別。

Date

Date的絕大部分API 都deprecated(過時)了,以下是目前可以使用的

 
Date()                     代表执行到这句构造函数时的当前时间
 
Date(long d)               用一个相对于1970 年 1 月 1 日 00:00:00 以来的走过的毫秒数创建时间对象。
                           如:new Date()  等价于   new Date(System.currentTimeMillis())
 
boolean before(Date when)  当前时间对象是否早于 when
boolean after(Date when)   当前时间对象是否晚于 when
toString()
hashCode()
equals()

Calender

Calendar 類是一個抽象類,它為特定瞬間與一組諸如YEAR、MONTH、DAY_OF_MON 、HOUR 等日曆欄位之間的轉換提供了一些方法,並為操作日曆欄位(例如獲得下週的日期)提供了一些方法。瞬間可用毫秒值來表示,它是距曆元(即格林威治標準時間 1970 年 1 月 1 日的 00:00:00.000,格里高利曆)的偏移量。 

該類別也為實現套件範圍外的特定日曆系統提供了其他欄位和方法。這些欄位和方法被定義為 protected。

具體可見API手冊。

SimpleDateFromat

SimpleDateFromat不是執行緒安全的,這是因為它繼承了DateFormat中的一個Calendar成員,每次在執行format操作時,都會改成成員calendar的狀態。這就是不安全的根源。

多執行緒下,很可能對Calendar的寫 和 讀 操作不同步(不是被同一個執行緒執行的),就會發生意外。

class DateFromat
{
  
     protected Calendar calendar;
     //...
}
 

SimpleDateFromat extends DateFromat
{

  private StringBuffer format(Date date, StringBuffer toAppendTo,FieldDelegate delegate)
  {
        // Convert input date to time field list
        calendar.setTime(date);
      //....

        //....
       

  }
}

下面開始介紹文章的主角類別。

  

DateUtils

提供了對時間物件的運算操作,就像和操作 int 一樣。

工具類,不允許建立實例

//-------------------静态字段-------------------
public static final long     MILLIS_PER_DAY     =    86400000L   一天的毫秒数
public static final long     MILLIS_PER_HOUR    =    3600000L    一个小时的毫秒数
public static final long     MILLIS_PER_MINUTE  =    60000L      一分钟的毫秒数
public static final long     MILLIS_PER_SECOND  =    1000L      一秒钟的毫秒数



//-------------------静态方法------------------
Date的运算和修改

static Date     addDays(Date date, int amount)          返回一个date 时间对象 添加 amount 天 后的新的Date 对象
static Date     addHours(Date date, int amount)         返回一个date 时间对象 添加 amount h 后的新的Date 对象
static Date     addMilliseconds(Date date, int amount)  返回一个date 时间对象 添加 amount 毫秒 后的新的Date 对象
static Date     addMinutes(Date date, int amount)       返回一个date 时间对象 添加 amount 分钟 后的新的Date 对象
static Date     addMonths(Date date, int amount)        返回一个date 时间对象 添加 amount 月 后的新的Date 对象
static Date     addSeconds(Date date, int amount)       返回一个date 时间对象 添加 amount 秒 后的新的Date 对象
static Date     addWeeks(Date date, int amount)         返回一个date 时间对象 添加 amount 周 后的新的Date 对象
static Date     addYears(Date date, int amount)         返回一个date 时间对象 添加 amount 年 后的新的Date 对象
static Date     setDays(Date date, int amount)          修改一个Date 对象的 天数 并返回新的Date对象。
static Date     setHours(Date date, int amount)         修改一个Date 对象的 小时字段并返回新的Date  
static Date     setMilliseconds(Date date, int amount)  修改一个Date 对象的 毫秒,并返回新的Date 对象
static Date     setMinutes(Date date, int amount)        修改一个Date 对象的 分钟
static Date     setMonths(Date date, int amount)         修改月份
static Date     setSeconds(Date date, int amount)        修改秒
static Date     setYears(Date date, int amount)          修改 年


字符串------>Date
从一个字符串str中按照 给定的字符串时间格式(见文章最后的SimpleDateFormat表),解析出一个时间对象。
可以给定多个字符串时间格式,依次尝试解析,如果都不能正确解析,则抛出java.text.ParseException异常。
如
DateUtils.parseDate("10-05-2016 12:45",Locale.CHINA, "dd-MM-yyyy HH:mm")
 

static Date  parseDate(String str, Locale locale, String... parsePatterns)
static Date  parseDate(String str, String... parsePatterns)
static Date  parseDateStrictly(String str, Locale locale, String... parsePatterns)
static Date  parseDateStrictly(String str, String... parsePatterns)






对时间的向上取整,截断,四舍五入,和 对浮点数的操作机制一样。
对一个时间对象的某个字段进行向上取整。 filed指定取整的字段,可以取的值为

Calendar.SECOND
Calendar.MINUTE
Calendar.HOUR_OF_DAY
Calendar.DAY_OF_MONTH
Calendar.MONTH
Calendar.YEAR   等...

如时间为:2016-2-12 22:17:48,若对年进行向上取整(ceiling),则看传入的参数的月份,为2,向上取值为年底,则会变为2017年
2017-1-1 0:00:00

如时间为:2016-2-25 22:17:48,若对月进行截断取整(truncate),则看传入的参数的天,为12,直接丢弃,则会变为本月第一天
2016-2-1 0:00:00

static Calendar  ceiling(Calendar date, int field)
static Date      ceiling(Date date, int field)



static Calendar  round(Calendar date, int field)      和ceil同理,round 是四舍五入
static Date      round(Date date, int field)



static Calendar truncate(Calendar date, int field)     对一个时间对象的某个字段进行截断。
static Date     truncate(Date date, int field)


static int     truncatedCompareTo(Calendar cal1, Calendar cal2, int field)      2个时间对象截断某个字段后比较,前者小返回-1,相同返回0,否则返回1
static int     truncatedCompareTo(Date date1, Date date2, int field)



static boolean     truncatedEquals(Calendar cal1, Calendar cal2, int field)     2个时间对象截断某个字段后比较,相同返回true,否则返回false
static boolean     truncatedEquals(Date date1, Date date2, int field)


 
将Date 转换为Calendar
static Calendar    toCalendar(Date date)  


时间 对象的 想等/相近 比较
static boolean     isSameDay(Calendar cal1, Calendar cal2)         是否是同一天,而不在乎具体时间,如 2月12 18:00 和 2月12 23:35 都是一天
static boolean     isSameDay(Date date1, Date date2)               是否是同一天,而不在乎具体时间,如 2月12 18:00 和 2月12 23:35 都是一天
static boolean     isSameInstant(Calendar cal1, Calendar cal2)     是否完全代表同一个时刻,相同。
static boolean     isSameInstant(Date date1, Date date2)           是否完全代表同一个时刻,相同。

DateFormatUtils

 

將時間轉換為字串的工具類。不可實例化物件。

線程安全。

這個類別中的所有重載的format 實質都是調了下面2個函數。而這2個函數中又藉用了FastDateFormat的API。

FastDateFormat是apache time util  優於Java  SimpleDateFormat 的核心類別。它是線程安全的。

public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) {
    final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
    return df.format(date);
}

    
    
public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone, final Locale locale) {
    final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
    return df.format(calendar);
}
时间参数  可以是Date 对象  ,Calender 对象  ,或者一个相对于1970年的long整数

pattern ,如:"yyyy-MM-dd HH:mm:ss"    参见文章最后SimpleDateFormat格式表

Locale:地理,政治和文化地区 如Locale.CHINA

TimeZone:时区偏移量.     
   TimeZone.getTimeZone("GMT+:08:00");   北京时间
   TimeZone.getDefault()                 默认



static String     format(Calendar calendar, String pattern)

static String     format(Calendar calendar, String pattern, Locale locale)

static String     format(Calendar calendar, String pattern, TimeZone timeZone)

static String     format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale)

static String     format(Date date, String pattern)

static String     format(Date date, String pattern, Locale locale)

static String     format(Date date, String pattern, TimeZone timeZone)

static String     format(Date date, String pattern, TimeZone timeZone, Locale locale)

static String     format(long millis, String pattern)

static String     format(long millis, String pattern, Locale locale)

static String     format(long millis, String pattern, TimeZone timeZone)

static String     format(long millis, String pattern, TimeZone timeZone, Locale locale)

static String     formatUTC(Date date, String pattern)

static String     formatUTC(Date date, String pattern, Locale locale)

static String     formatUTC(long millis, String pattern)

static String     formatUTC(long millis, String pattern, Locale locale)

DateUtils 在parse時內部利用了java自身的SimpleDateFormat(即便如此,DateUtils的操作都是是線程安全的,因為SimpleDateFromat是作為方法的局部變數所使用的),而DateFormatUtils 則利用了apache開發的線程安全的FastDateFromat。因此,DateUtils和DateFormatUtils可以滿足簡單的時間操作了。如果需要更多的客製化操作,就可能需要

下面介紹的FastDateFormat了。

FastDateFormat

 FastDateFormat是一個快速 且 線程安全的時間操作類,它完全可以替代SimpleDateFromat。

 因為是線程安全的,所以你可以把它作為一個類別的靜態字段使用

 構造函數為protected,不允許直接構造它的對象,可以透過工廠方法獲取。

 

FastDateFormat之所以是線程安全的,是因為這個類別是無狀態的:內部的成員在構造時就完成了初始化,並在對象存活期,不提供任何API供外界修改他們。

FastDateFormat內部有​​很重要的2個物件:

FastDateParser

FastDatePrinter

分別完成解析和format工作。他們也都是線程安全的,都修飾為final。有興趣的可以取讀原始碼。

静态字段
 
用于构造时,控制时间或者日期显示的完整性,FULL最完整,SHORT最次。
static int     FULL      表示完全显示

static int     LONG      

static int     MEDIUM  

static int     SHORT    

 
构造
static FastDateFormat     getDateInstance(int style)
static FastDateFormat     getDateInstance(int style, Locale locale)
static FastDateFormat     getDateInstance(int style, TimeZone timeZone)
static FastDateFormat     getDateInstance(int style, TimeZone timeZone, Locale locale)
只控制日期显示格式
使用style指定的日期显示的完整性,静态字段提供
timeZone 指定时区,若不指定,则使用系统默认的
locale   指定 国家区域,若不指定,则使用系统默认的
 



static FastDateFormat     getInstance()
static FastDateFormat     getInstance(String pattern)
static FastDateFormat     getInstance(String pattern, Locale locale)
static FastDateFormat     getInstance(String pattern, TimeZone timeZone)
static FastDateFormat     getInstance(String pattern, TimeZone timeZone, Locale locale)
通过String类型的pattern自定义显示格式
String类型的pattern 指定format格式,参见SimpleDateFormat
timeZone 指定时区,若不指定,则使用系统默认的
locale   指定 国家区域,若不指定,则使用系统默认的
 
 
 
static FastDateFormat     getDateTimeInstance(int dateStyle, int timeStyle)
static FastDateFormat     getDateTimeInstance(int dateStyle, int timeStyle, Locale locale)
static FastDateFormat     getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone)
static FastDateFormat     getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone, Locale locale)
同时控制 日期和 时间的显示格式
使用style指定的日期和时间显示的完整性,静态字段提供
 
 

StringBuffer     format(Date date, StringBuffer buf)
StringBuffer     format(long millis, StringBuffer buf)
StringBuffer     format(Calendar calendar, StringBuffer buf)
将格式化后的字符串写入到一个StringBuffer对象中
 

String     format(long millis)
String     format(Date date)
String     format(Calendar calendar)

Date     parse(String source)
Date     parse(String source, ParsePosition pos)
从字符串解析一个Date,解析的模式是构造时决定的

 
String     getPattern()   获取fommat时的pattern

TimeZone   getTimeZone()    

Locale     getLocale()

範例:

import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.time.FastDateFormat;


/**
 * 当使用FastDateFormat.getInstance()构造时,需要和SimpleDateFomat一样,自定义格式化字符串。
 * 当使用FastDateFormat.getDateTimeInstance() 构造时,需要 FastDateFormat的4个静态字段指定日期 和 时间显示的具体程度
 * 当使用FastDateFormat.getDateInstance() 构造时,意为着你只想显示日期,需要 FastDateFormat的4个静态字段指定日期的显示的具体程度
 *
 */

public class Test {

    
    public static void showCustom()
    {
        
        String pattern = "yyyy-MM-dd HH:mm:ss";
        
        final FastDateFormat df = FastDateFormat.getInstance(pattern);
        
        System.out.println(df.format(new Date()));
        
    }
    
    public static void showDateAndTime()
    {
        final FastDateFormat df = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL,
                                                                    FastDateFormat.FULL,
                                                                    Locale.CHINA);
        System.out.println(df.format(new Date()));
         
        
    }
    public static void showDate()
    {
        final FastDateFormat df = FastDateFormat.getDateInstance(FastDateFormat.LONG, Locale.CHINA);
        
        System.out.println(df.format(new Date()));
        
    }
    
    
    
    
    public static void main(String[] args) 
    {
        
        showCustom();
        
        showDateAndTime();
        
        showDate();
        
        
        /*Output
         * 
         *  2016-10-15 16:18:49
            2016年10月15日 星期六 下午04时18分49秒 CST
            2016年10月15日

         */
        
    }

}

SimpleDateFormat的時間字串表現模式定義表

使用apache.lang套件安全簡潔地操作Java時間

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn