Java本身的日期类在JDK1.0版本之后就再也没有更新过,同时还存在着一些众所周知的问题(例如1月从0开始,导致了很多月份差一的漏洞)。一份新的Java规范请求(JSR,Java Specification Request)已经被提交,目的就是要解决上述问题,此版本的类库仍处在Alpha版本。在其稳定之前,很多开发者还是会使用Joda Time类库,该类库与JSR-310的参考实现类似(但不完全相同)。 Date4j为在Java中处理日期提供了一套新的解决方案,但与Joda Time所关注的范围完全不同。对比如下:
-----------------------------------------------------------------------------------------------------------------------------------------------------------
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 09999
* @param aNumMonths
* positive, required, in range 09999
* @param aNumDays
* positive, required, in range 09999
* @param aNumHours
* positive, required, in range 09999
* @param aNumMinutes
* positive, required, in range 09999
* @param aNumSeconds
* positive, required, in range 09999 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
}
}