近期一直做的几个功能都跟日期处理有关。比方推断今天是否登录。今天的最小时间。今天结束的最大时间等。
代码中都是用的JDK自带的 Calendar,使用起来相当费劲了,于是乎,忍不了,找到了一个名叫:JodaTime 的库,
眼下Joda Time 已经纳入 JDK 8 的官方API了,可是JDK 8还是非常遥远。以下我给大家演示几个实例:
1、 获取今天的開始时间:比方:2014-06-19 00:00:00
Joda Time |
JDK |
DateTime nowTime = new DateTime(); DateTime startOfDay = nowTime.withTimeAtStartOfDay(); |
Calendar c1 = Calendar.getInstance(); c1.setTimeInMillis(timeInMs); c1.set(Calendar.HOUR_OF_DAY, 0); c1.set(Calendar.MINUTE, 0); c1.set(Calendar.SECOND, 0); c1.set(Calendar.MILLISECOND, 0); return c1.getTimeInMillis(); |
2、 获取今天的结束时间:比方:2014-06-19 23:59:59
Joda Time |
JDK |
DateTime nowTime = new DateTime(); DateTime endOfDay = nowTime.millisOfDay().withMaximumValue(); |
Calendar c1 = Calendar.getInstance(); c1.setTimeInMillis(timeInMs); c1.set(Calendar.HOUR_OF_DAY, 23); c1.set(Calendar.MINUTE, 59); c1.set(Calendar.SECOND, 59); c1.set(Calendar.MILLISECOND, 0); return c1.getTimeInMillis(); |
3、 获取如今距离今天结束还有多长时间
DateTimenowTime = new DateTime();
DateTime endOfDay = nowTime.millisOfDay().withMaximumValue();
endOfDay.getMillis()-nowTime.getMillis()
4、 计算两个日期的相隔天数
Joda Time |
JDK |
DateTime nowTime = new DateTime(); DateTime futureTime = new DateTime(2015, 10, 1, 0, 0, 0); Int days = Days.daysBetween(nowTime, futureTime).getDays(); |
(实现不是非常好) public static int getBetweenDay(long startTime, long endTime) { Calendar start = Calendar.getInstance(); start.setTimeInMillis(startTime);
Calendar end = Calendar.getInstance(); end.setTimeInMillis(endTime);
return (int) ((end.getTimeInMillis() - start.getTimeInMillis()) / 86400000); } |
还有非常多比較方便的功能,能够自己去尝试。
推荐文章:http://www.ibm.com/developerworks/cn/java/j-jodatime.html
官方地址:http://www.joda.org/joda-time/
Maven 仓库:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>