0

0

使用apache.lang包安全简洁地操作Java时间

高洛峰

高洛峰

发布时间:2016-10-15 17:34:58

|

2109人浏览过

|

来源于php中文网

原创

在这之前还是先简单说一下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_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。 

该类还为实现包范围外的具体日历系统提供了其他字段和方法。这些字段和方法被定义为 protected。

具体可见API手册。

SimpleDateFromat

SimpleDateFromat不是线程安全的,这是因为它继承了DateFormat中的一个Calendar成员,每次在执行format操作时,都会改成成员calendar的状态。这就是不安全的根源。

立即学习Java免费学习笔记(深入)”;

多线程下,很可能对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 的核心类。它是线程安全的。

ShoopD 网上商店系统
ShoopD 网上商店系统

用 php + mysql 驱动的在线商城系统,我们的目标为中国的中小企业及个人提供最简洁,最安全,最高效的在线商城解决方案,使用了自建的会员积分折扣功能,不同的会员组有不同的折扣,让您的商店吸引更多的后续客户。 系统自动加分处理功能,自动处理会员等级,免去人工处理的工作量,让您的商店运作起来更方便省事 采用了自建的直接模板技术,免去了模板解析时间,提高了代码利用效率 独立开发的购物车系统,使用最

下载
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的时间字符串表达模式定义表

1.png

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Golang 测试体系与代码质量保障:工程级可靠性建设
Golang 测试体系与代码质量保障:工程级可靠性建设

Go语言测试体系与代码质量保障聚焦于构建工程级可靠性系统。本专题深入解析Go的测试工具链(如go test)、单元测试、集成测试及端到端测试实践,结合代码覆盖率分析、静态代码扫描(如go vet)和动态分析工具,建立全链路质量监控机制。通过自动化测试框架、持续集成(CI)流水线配置及代码审查规范,实现测试用例管理、缺陷追踪与质量门禁控制,确保代码健壮性与可维护性,为高可靠性工程系统提供质量保障。

48

2026.02.28

Golang 工程化架构设计:可维护与可演进系统构建
Golang 工程化架构设计:可维护与可演进系统构建

Go语言工程化架构设计专注于构建高可维护性、可演进的企业级系统。本专题深入探讨Go项目的目录结构设计、模块划分、依赖管理等核心架构原则,涵盖微服务架构、领域驱动设计(DDD)在Go中的实践应用。通过实战案例解析接口抽象、错误处理、配置管理、日志监控等关键工程化技术,帮助开发者掌握构建稳定、可扩展Go应用的最佳实践方法。

44

2026.02.28

Golang 性能分析与运行时机制:构建高性能程序
Golang 性能分析与运行时机制:构建高性能程序

Go语言以其高效的并发模型和优异的性能表现广泛应用于高并发、高性能场景。其运行时机制包括 Goroutine 调度、内存管理、垃圾回收等方面,深入理解这些机制有助于编写更高效稳定的程序。本专题将系统讲解 Golang 的性能分析工具使用、常见性能瓶颈定位及优化策略,并结合实际案例剖析 Go 程序的运行时行为,帮助开发者掌握构建高性能应用的关键技能。

37

2026.02.28

Golang 并发编程模型与工程实践:从语言特性到系统性能
Golang 并发编程模型与工程实践:从语言特性到系统性能

本专题系统讲解 Golang 并发编程模型,从语言级特性出发,深入理解 goroutine、channel 与调度机制。结合工程实践,分析并发设计模式、性能瓶颈与资源控制策略,帮助将并发能力有效转化为稳定、可扩展的系统性能优势。

22

2026.02.27

Golang 高级特性与最佳实践:提升代码艺术
Golang 高级特性与最佳实践:提升代码艺术

本专题深入剖析 Golang 的高级特性与工程级最佳实践,涵盖并发模型、内存管理、接口设计与错误处理策略。通过真实场景与代码对比,引导从“可运行”走向“高质量”,帮助构建高性能、可扩展、易维护的优雅 Go 代码体系。

19

2026.02.27

Golang 测试与调试专题:确保代码可靠性
Golang 测试与调试专题:确保代码可靠性

本专题聚焦 Golang 的测试与调试体系,系统讲解单元测试、表驱动测试、基准测试与覆盖率分析方法,并深入剖析调试工具与常见问题定位思路。通过实践示例,引导建立可验证、可回归的工程习惯,从而持续提升代码可靠性与可维护性。

3

2026.02.27

漫蛙app官网链接入口
漫蛙app官网链接入口

漫蛙App官网提供多条稳定入口,包括 https://manwa.me、https

268

2026.02.27

deepseek在线提问
deepseek在线提问

本合集汇总了DeepSeek在线提问技巧与免登录使用入口,助你快速上手AI对话、写作、分析等功能。阅读专题下面的文章了解更多详细内容。

51

2026.02.27

AO3官网直接进入
AO3官网直接进入

AO3官网最新入口合集,汇总2026年可用官方及镜像链接,助你快速稳定访问Archive of Our Own平台。阅读专题下面的文章了解更多详细内容。

430

2026.02.27

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
MySQL 初学入门(mosh老师)
MySQL 初学入门(mosh老师)

共3课时 | 0.3万人学习

php初学者入门课程
php初学者入门课程

共10课时 | 0.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号