首页 > 代码库 > Joda Time 使用

Joda Time 使用

    最近一直做的几个功能都跟日期处理有关,比如判断今天是否登录,今天的最小时间,今天结束的最大时间等。

    代码中都是用的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>