>  기사  >  类库下载  >  apache.lang 패키지를 사용하여 Java 시간을 안전하고 간결하게 조작하세요.

apache.lang 패키지를 사용하여 Java 시간을 안전하고 간결하게 조작하세요.

高洛峰
高洛峰원래의
2016-10-15 17:34:581796검색

그 전에 Java 자체의 시간 처리 클래스에 대해 간단히 이야기하겠습니다.

날짜

날짜의 대부분의 API는 더 이상 사용되지 않습니다(오래됨). 다음은 현재 사용 가능한

 
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()

캘린더

캘린더 클래스입니다. 특정 순간과 YEAR, MONTH, DAY_OF_MONTH, HOUR 등과 같은 달력 필드 집합 사이를 변환하기 위한 몇 가지 메서드를 제공하고 달력 필드를 작동하기 위한 몇 가지 메서드(예: 다음 주의 날짜 가져오기)를 제공하는 추상 클래스 . 순간은 에포크(그레고리력 1970년 1월 1일 GMT 00:00:00.000)로부터의 오프셋인 밀리초 값으로 표현될 수 있습니다.

이 클래스는 패키지 범위 외부에서 특정 달력 시스템을 구현하기 위한 추가 필드와 메서드도 제공합니다. 이러한 필드와 메소드는 보호된 것으로 정의됩니다.

자세한 내용은 API 매뉴얼을 참고하세요.

SimpleDateFromat

SimpleDateFromat은 DateFormat의 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

시간을 문자열로 변환하는 유틸리티 클래스입니다. 인스턴스화할 수 없는 객체.

스레드 안전.

이 클래스의 모든 오버로드된 형식은 기본적으로 다음 두 가지 기능을 조정합니다. 이 두 함수는 FastDateFormat의 API를 차용합니다.

FastDateFormat은 Java SimpleDateFormat보다 뛰어난 Apache Time util의 핵심 클래스입니다. 스레드로부터 안전합니다.

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는 구문 분석 시 내부적으로 Java 자체 SimpleDateFormat을 활용하며(그래도 SimpleDateFromat가 메소드의 로컬 변수로 사용되므로 DateUtils의 작업은 스레드로부터 안전합니다) DateFormatUtils는 스레드를 활용합니다 -Apache에서 개발한 안전한 FastDateFromat입니다. 따라서 DateUtils 및 DateFormatUtils는 간단한 시간 연산을 충족할 수 있습니다. 더 많은 사용자 정의 작업이 필요한 경우 아래에 소개된

FastDateFormat이 필요할 수 있습니다.

FastDateFormat

FastDateFormat은 SimpleDateFromat을 완전히 대체할 수 있는 빠르고 스레드로부터 안전한 시간 작업 클래스입니다.

스레드로부터 안전하기 때문에 클래스의 정적 필드로 사용할 수 있습니다.

생성자는 보호되며 객체를 직접 생성하는 것을 허용하지 않습니다. 공장 방식.

FastDateFormat이 스레드로부터 안전한 이유는 이 클래스가 상태 비저장이기 때문입니다. 내부 멤버는 생성 중에 초기화되며 객체 수명 동안 외부인이 수정할 수 있는 API를 제공하지 않습니다. .

FastDateFormat에는 매우 중요한 두 개체가 있습니다.

FastDateParser

FastDatePrinter

는 각각 구문 분석 및 서식 지정 작업을 완료합니다. 또한 스레드로부터 안전하며 최종 버전으로 수정됩니다. 관심 있는 분들은 소스코드를 읽어보시면 됩니다.

静态字段
 
用于构造时,控制时间或者日期显示的完整性,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으로 문의하세요.