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

从一个字符串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 的核心类。它是线程安全的。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/20f324c1df0aaf72b4e2128182af2634.html