关于date4j,简约的日期处理库(Java's Date Classes Must Die.)
在熟悉公司业务代码的时候经常看见有日期处理(date),由于项目转手次数较多,在这方面没合理封装处理好,于是就想自己封装一个date类。然而辗转了几天却发觉已经有date4j的存在,于是在这里简单地介绍一下这个日期类库。以下包括自己的代码、网上流传资料、以及date4j官网例子。
-------------------------------------------------------------------------------------------------------------------------------------------------------------
java日期处理相关类:
java.sql.Date
java.sql.Time
java.sql.Timestamp
java.util.Calendar
java.util.TimeZone
比较常用的是java.util.date,将java.util.Date转为java.sql.Date的时候,日期时分秒会被去掉,失去精度。而且如果现在翻开api看看就发觉这两个类好多方法已经过时,几近沦为废物。
Timestamp能和java.util.date无损转换,但是在一些预定义sql中会常常出问题。
(以上出自 click me)
--------------------------------------------------------------------------------------------------------------------------------------------------------------
Joda Time | Date4j |
---|---|
拥有的类的数量: 140+ | 拥有的类的数量 < 10 |
包含可变和不可变类 | 仅包含不可变类 |
强调速度和功能 | 强调简单和有效 |
支持格里高里历(Gregorian)、 科普特语日历(Coptic)、 伊斯兰教历(Islamic)、佛历(Buddhist)等等 | 只提供对格里高里历的支持 |
可以完全取代JDK日期类 | 和JDK日期类配合使用 |
精确到毫秒级操作 | 支持到纳秒(十亿分之一秒)级操作 |
修复了天“溢出”的问题 | 天“溢出”的问题可配置 |
针对的是通常意义的日期维护 | 适用于通过数据库来维护的日期 |
采用Apache 2.0授权许可 | 采用BSD授权许可 |
虽然乍一看Date4j只具备了Joda中一部分的特性,但它有两个主要的特点是Joda所不具备的。
首先,Date4j的开发者 宣称类库不应莫名其妙地将日期截断。Joda只支持毫秒级的精度而且在将来 可能也不会改善。一些数据库也已经有了更好的解决方案。比如流行的 PostgreSQL数据库对时间戳精度就已经支持到 微秒级(百万分之一秒)。Date4j可在处理日期时对精度毫无损伤。
第二个特征是日期“溢出”的问题,例如向某个日期增加一段时间后,日期落在下月的情况。最简单的例子就是在3月31日增加一个月的计算:
DateTime dt = new DateTime("2011-03-31");
DateTime result = dt.plusMonths(1); (最新版本此方法应该已经被删除,只有plus(...)与plusDay())
System.out.println(result.toString());
当使用Joda Time时,会输出4月30日,但这也许并不是你想要的结果。
鉴于这种不确定性,Date4j为您提供了 4种选择:
1. | 第一天 |
2. | 最后一天(与Joda Time相同) |
3. | 日期顺延 |
4. | 抛出异常 |
以上转自 click me
-----------------------------------------------------------------------------------------------------------------------------------------------------------
date4j官网&&实例:
import hirondelle.date4j.DateTime;
import hirondelle.date4j.DateTime.DayOverflow;
import java.util.TimeZone;
public class Date4jExamples {
public static void main(String[] args) {
Date4jExamples examples = new Date4jExamples();
examples.currentDateTime();
examples.ageIfBornOnCertainDate();
examples.daysTillChristmas();
examples.whenIs90DaysFromToday();
examples.dateDifference();
examples.whenIs3Months5DaysFromToday();
examples.hoursDifferenceBetweenParisAndPerth();
examples.weeksSinceStart();
examples.timeTillMidnight();
examples.imitateISOFormat();
examples.firstDayOfThisWeek();
examples.jdkDatesSuctorial();
}
private static void log(Object aMsg) {
System.out.println(String.valueOf(aMsg));
}
/**
* 获取当前时间 what is the current date-time in the JRE's default time zone
* ------------------------------------------------------------------------
* Here are some practical examples of using the above formatting symbols:
* Format Output YYYY-MM-DD hh:mm:ss.fffffffff a 1958-04-09
* 03:05:06.123456789 AM YYYY-MM-DD hh:mm:ss.fff a 1958-04-09 03:05:06.123
* AM YYYY-MM-DD 1958-04-09 hh:mm:ss.fffffffff 03:05:06.123456789 hh:mm:ss
* 03:05:06 YYYY-M-D h:m:s 1958-4-9 3:5:6 WWWW, MMMM D, YYYY Wednesday,
* April 9, 1958 WWWW, MMMM D, YYYY |at| D a Wednesday, April 9, 1958 at 3
* AM ----------------------------------------------------------------------
* ---
*/
private void currentDateTime() {
DateTime now = DateTime.now(TimeZone.getDefault());
String result = now.format("YYYY-MM-DD hh:mm:ss");
log("Current date-time in default time zone : " + result);
// result Current date-time in default time zone : 2012-04-12 00:55:54
}
/**
* 年龄计算 what's the age of someone born may 16,1995
*/
private void ageIfBornOnCertainDate() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime birthdate = DateTime.forDateOnly(1995, 5, 16);
int age = today.getYear() - birthdate.getYear();
// getDayOfYear获取距离年初的总天数
if (today.getDayOfYear() < birthdate.getDayOfYear()) {
age = age - 1;
}
log("Age of someone born May 16, 1995 is : " + age);
// result Age of someone born May 16, 1995 is : 16
}
/**
* 日期相距 How many days till the next December 25
*/
private void daysTillChristmas() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime christmas = DateTime.forDateOnly(today.getYear(), 12, 25);
int result = 0;
if (today.isSameDayAs(christmas)) {
// do nothing
} else if (today.lt(christmas)) {
result = today.numDaysFrom(christmas);
} else if (today.gt(christmas)) {
DateTime christmasNextYear = DateTime.forDateOnly(
today.getYear() + 1, 12, 25);
result = today.numDaysFrom(christmasNextYear);
}
log("Number of days till Christmas : " + result);
// result Number of days till Christmas : 257
}
/**
* What day is 90 days from today
*/
private void whenIs90DaysFromToday() {
DateTime today = DateTime.today(TimeZone.getDefault());
log("90 days from today is : "
+ today.plusDays(90).format("YYYY-MM-DD"));
// result 90 days from today is : 2012-07-11
}
/**
* 日期相差
*/
private void dateDifference() {
// DayOverflow.Abort result throw Exception
// DayOverflow.Spillover result 2011-05-01
// DayOverflow.LastDay result 2011-04-30
// DayOverflow.FirstDay result 2011-05-01
// public enum DayOverflow {
/** Coerce the day to the last day of the month. */
// LastDay,
/** Coerce the day to the first day of the next month. */
// FirstDay,
/** Spillover the day into the next month. */
// Spillover,
/** Throw a RuntimeException. */
// Abort;
// }
/**
* @param aNumYears
* positive, required, in range 0 9999
* @param aNumMonths
* positive, required, in range 0 9999
* @param aNumDays
* positive, required, in range 0 9999
* @param aNumHours
* positive, required, in range 0 9999
* @param aNumMinutes
* positive, required, in range 0 9999
* @param aNumSeconds
* positive, required, in range 0 9999 method plus(Integer
* aNumYears, Integer aNumMonths, Integer aNumDays, Integer
* aNumHours, Integer aNumMinutes, Integer aNumSeconds,
* DayOverflow aDayOverflow)
*
*/
DateTime dt = new DateTime("2011-03-31");
DateTime result = dt.plus(0, 1, 0, 0, 0, 0, DayOverflow.Spillover);
log("date difference : " + result.toString());
// result date difference : 2011-05-01 00:00:00
}
/** What day is 3 months and 5 days from today? */
private void whenIs3Months5DaysFromToday() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime result = today.plus(0, 3, 5, 0, 0, 0,
DateTime.DayOverflow.FirstDay);
log("3 months and 5 days from today is : "
+ result.format("YYYY-MM-DD"));
// result 3 months and 5 days from today is : 2012-07-17
}
/**
* Current number of hours difference between Paris, France and Perth,
* Australia.
*/
private void hoursDifferenceBetweenParisAndPerth() {
// this assumes the time diff is a whole number of hours; other styles
// are possible
DateTime paris = DateTime.now(TimeZone.getTimeZone("Europe/Paris"));
DateTime perth = DateTime.now(TimeZone.getTimeZone("Australia/Perth"));
int result = perth.getHour() - paris.getHour();
if (result < 0) {
result = result + 24;
}
log("Numbers of hours difference between Paris and Perth : " + result);
// result Numbers of hours difference between Paris and Perth : 6
}
/** How many weeks is it since Sep 6, 2010? */
private void weeksSinceStart() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime startOfProject = DateTime.forDateOnly(2010, 9, 6);
int result = today.getWeekIndex() - startOfProject.getWeekIndex();
log("The number of weeks since Sep 6, 2010 : " + result);
// result The number of weeks since Sep 6, 2010 : 83
}
/** How much time till midnight? */
private void timeTillMidnight() {
DateTime now = DateTime.now(TimeZone.getDefault());
DateTime midnight = now.plusDays(1).getStartOfDay();
long result = now.numSecondsFrom(midnight);
log("This many seconds till midnight : " + result);
// result This many seconds till midnight : 83046
}
/** Format using ISO style. */
private void imitateISOFormat() {
DateTime now = DateTime.now(TimeZone.getDefault());
log("Output using an ISO format: " + now.format("YYYY-MM-DDThh:mm:ss"));
// result Output using an ISO format: 2012-04-12T00:55:54
}
private void firstDayOfThisWeek() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime firstDayThisWeek = today; // start value
int todaysWeekday = today.getWeekDay();
int SUNDAY = 1;
if (todaysWeekday > SUNDAY) {
int numDaysFromSunday = todaysWeekday - SUNDAY;
firstDayThisWeek = today.minusDays(numDaysFromSunday);
}
log("The first day of this week is : " + firstDayThisWeek);
// result The first day of this week is : 2012-04-08
}
/** For how many years has the JDK date-time API been suctorial? */
private void jdkDatesSuctorial() {
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime jdkFirstPublished = DateTime.forDateOnly(1996, 1, 23);
int result = today.getYear() - jdkFirstPublished.getYear();
log("The number of years the JDK date-time API has been suctorial : "
+ result);
// result The number of years the JDK date-time API has been suctorial :
// 16
}
}