Java日期简化工具Joda Time

英文官方文档:http://www.joda.org/joda-time/userguide.html

简介

想必大家在平时的项目开发中经常要处理日期的问题,比如需要处理两个日期间隔的天数,使用JDK1.8以前自带的日期API处理相当的繁琐(JDK1.8的API已经重写了日期库,其实也是借鉴了Joda-Time),那么接下来介绍的这款日期库工具(Joda-Time)就非常强大了,使用Joda-Time可以轻松的处理各种复杂的时间相关问题。

特点

  • 易于使用:使用Joda-Time可以非常容易的处理一些复杂的日期问题
  • 易于扩展:Joda-Time支持多达8种日历系统
  • 线程安全:Joda类具有不可变性,因此它们的实例无法被修改
  • 提供最新的时区计算
  • 互操作性:与JDK可互操作

类说明

  • Instant:不可变类,代表时间线上的一个唯一的时间点
  • DateTime:不可变类,它以毫秒级的精度封装时间上的某个瞬间时刻
  • LocalDate:不可变类,该类封装了一个年/月/日的组合。当地理位置(即时区)变得不重要时,使用它存储日期将非常方便
  • LocalTime:不可变类,这个类封装一天中的某个时间,当地理位置不重要的情况下,可以使用这个类来只存储一天当中的某个时间
  • LocalDateTime:不可变类,该类封装了一个年/月/日 时:分:秒的组合。当地理位置(即时区)变得不重要时,使用它存储日期和时间非常方便

使用示例

(1)使用maven导入Joda-Time包

<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.9</version>
</dependency>

(2)DateTime使用

如需输出当前日期和时间

DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
//本月多少号
int dayOfMonth = dateTime.getDayOfMonth();
//本年的第几月
int monthOfYear = dateTime.getMonthOfYear();
//获取年份
int year = dateTime.getYear();
//当前日期+1天后的时间
dateTime = dateTime.plusDays(1);
//当前日期+1小时的时间
dateTime = dateTime.plusHours(1);
//当前日期-1年前的时间
dateTime = dateTime.plusYears(-1);
//创建指定日期时间如:2017-2-28 10:40:50:500
DateTime dateTime = new DateTime(2017,2,28,10,40,50,500);

3)LocalDate使用

该类代表没有时区的日期,适用与对时区不关心的日期场景

LocalDate localDate = new LocalDate();
LocalDate lDate = new LocalDate(2017,12,12);

4)LocalTime使用

该类代表没有时区的时间,适用与对时区不关心的时间场景

LocalTime localTime = new LocalTime();
LocalTime lTime = new LocalTime(12,20,10);

(5)LocalDateTime使用

该类代表没有时区的日期时间,适用与对时区不关心的日期时间场景

LocalDateTime localDateTime = new LocalDateTime();
//2017-12-12 13:10:18
LocalDateTime localDateTime2 = new LocalDateTime(2017,12,12,13,10,18);

(6)与JDK互操作/java jode time时区换算

//取得日本時區
DateTimeZone gmt = DateTimeZone.forID( "Asia/Tokyo" );
 
//轉換為DateTime物件
DateTime datetime = new DateTime(gmt);
 
//轉換為Java Date物件
Date date = datetime.toLocalDateTime().toDate();
Date date = dateTime.toDate();
Calendar calendar = dateTime.toCalendar(Locale.CHINESE);
//通过jdk时间对象构造  
Date date = new Date();  
DateTime dateTime = new DateTime(date);  
  
Calendar calendar = Calendar.getInstance();  
dateTime = new DateTime(calendar);  
  
// Joda-time 各种操作.....  
dateTime = dateTime.plusDays(1) // 增加天  
                    .plusYears(1)// 增加年  
                    .plusMonths(1)// 增加月  
                    .plusWeeks(1)// 增加星期  
                    .minusMillis(1)// 减分钟  
                    .minusHours(1)// 减小时  
                    .minusSeconds(1);// 减秒数  
                      
// 计算完转换成jdk 对象  
Date date2 = dateTime.toDate();  
Calendar calendar2 = dateTime.toCalendar(Locale.CHINA);

(7)综合使用

LocalDate localDate = new LocalDate();
//计算下一个月的第一天的日期
localDate = localDate.plusMonths(1).dayOfMonth().withMinimumValue();
DateTime dateTime = new DateTime();
//计算一年前的第二个月的最后一天的日期
DateTime dateTime = dateTime.minusYears(1) // 一年前
      .monthOfYear()     // 获得 monthOfYear 属性
      .setCopy(2)        // 设置为2月
      .dayOfMonth()      // 获得 dayOfMonth 属性
      .withMaximumValue();// 一个月中的最后一天

(8)简化类

package com.laurel.demo.jodatime;

import org.joda.time.DateTime;

import java.util.Date;

public class DateUtils {

    public static Date makeDate(Date date, int hour, int minute, int second) {
        DateTime dateTime = new DateTime(date);
        return new DateTime(dateTime.getYear(),
                            dateTime.getMonthOfYear(),
                            dateTime.getDayOfMonth(),
                            hour,
                            minute,
                            second).toDate();
    }

    /**
     * 制作开始时间
     * @param date 日期
     * @return 形如:2016-05-29 00:00:00
     */
    public static Date makeBeginDate(Date date) {
        return makeDate(date, 0, 0, 0);
    }

    /**
     * 制作结束时间
     * @param date 日期
     * @return 形如:2016-05-29 23:59:59
     */
    public static Date makeEndDate(Date date) {
        return makeDate(date, 23, 59, 59);
    }

    /**
     * 获取n天之后的时间
     * @param date 日期
     * @param days n天,可正可负
     * @return
     */
    public static Date getNextNDay(Date date, int days) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    /**
     * 格式化日期
     * @param date 日期
     * @param pattern 日期格式
     * @return
     */
    public static String format(Date date, String pattern) {
        return new DateTime(date).toString(pattern);
    }

    /**
     * 格式化日期(年月日)
     * @param date 日期
     * @return
     */
    public static String dateFormat(Date date) {
        return new DateTime(date).toString("yyyy-MM-dd");
    }

    /**
     * 格式化日期(年月日 时分秒)
     * @param date 日期
     * @return
     */
    public static String sencondFormat(Date date) {
        return new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
    }
}
    package com.yan.joda;  
      
    import java.util.Calendar;  
    import java.util.Date;  
    import java.util.Locale;  
    import org.joda.time.DateTime;  
    import org.joda.time.Days;  
    import org.joda.time.LocalDate;  
    import org.joda.time.format.DateTimeFormat;  
    import org.joda.time.format.DateTimeFormatter;  
      
    public class JodaTest {  
      
        public static void main(String[] args) {  
            //初始化时间  
                    DateTime dateTime=new DateTime(2012, 12, 13, 18, 23,55);  
                      
                    // 年,月,日,时,分,秒,毫秒    
                    DateTime dt3 = new DateTime(2011, 2, 13, 10, 30, 50, 333);// 2010年2月13日10点30分50秒333毫秒  
                      
                    //下面就是按照一点的格式输出时间  
                    String str2 = dateTime.toString("MM/dd/yyyy hh:mm:ss.SSSa");  
                    String str3 = dateTime.toString("dd-MM-yyyy HH:mm:ss");  
                    String str4 = dateTime.toString("EEEE dd MMMM, yyyy HH:mm:ssa");  
                    String str5 = dateTime.toString("MM/dd/yyyy HH:mm ZZZZ");  
                    String str6 = dateTime.toString("MM/dd/yyyy HH:mm Z");  
                      
                    DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd HH:mm:ss");  
                    //时间解析    
                    DateTime dateTime2 = DateTime.parse("2012-12-21 23:22:45", format);    
                        
                    //时间格式化,输出==> 2012/12/21 23:22:45 Fri    
                    String string_u = dateTime2.toString("yyyy/MM/dd HH:mm:ss EE");    
                    System.out.println(string_u);    
                        
                    //格式化带Locale,输出==> 2012年12月21日 23:22:45 星期五    
                    String string_c = dateTime2.toString("yyyy年MM月dd日 HH:mm:ss EE",Locale.CHINESE);    
                    System.out.println(string_c);  
                      
                    DateTime dt1 = new DateTime();// 取得当前时间  
                       
                    // 根据指定格式,将时间字符串转换成DateTime对象,这里的格式和上面的输出格式是一样的    
                    DateTime dt2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("2012-12-26 03:27:39");  
                      
                    //计算两个日期间隔的天数  
                    LocalDate start=new LocalDate(2012, 12,14);    
                    LocalDate end=new LocalDate(2013, 01, 15);    
                    int days = Days.daysBetween(start, end).getDays();  
                      
                    //计算两个日期间隔的小时数,分钟数,秒数  
                      
                    //增加日期  
                    DateTime dateTime1 = DateTime.parse("2012-12-03");  
                    dateTime1 = dateTime1.plusDays(30);  
                    dateTime1 = dateTime1.plusHours(3);  
                    dateTime1 = dateTime1.plusMinutes(3);  
                    dateTime1 = dateTime1.plusMonths(2);  
                    dateTime1 = dateTime1.plusSeconds(4);  
                    dateTime1 = dateTime1.plusWeeks(5);  
                    dateTime1 = dateTime1.plusYears(3);  
                      
                    // Joda-time 各种操作.....    
                    dateTime = dateTime.plusDays(1) // 增加天    
                                        .plusYears(1)// 增加年    
                                        .plusMonths(1)// 增加月    
                                        .plusWeeks(1)// 增加星期    
                                        .minusMillis(1)// 减分钟    
                                        .minusHours(1)// 减小时    
                                        .minusSeconds(1);// 减秒数  
                      
                    //判断是否闰月    
                    DateTime dt4 = new DateTime();    
                    org.joda.time.DateTime.Property month = dt4.monthOfYear();    
                    System.out.println("是否闰月:" + month.isLeap());  
                      
                    //取得 3秒前的时间    
                    DateTime dt5 = dateTime1.secondOfMinute().addToCopy(-3);    
                    dateTime1.getSecondOfMinute();// 得到整分钟后,过的秒钟数    
                    dateTime1.getSecondOfDay();// 得到整天后,过的秒钟数    
                    dateTime1.secondOfMinute();// 得到分钟对象,例如做闰年判断等使用  
                      
                    // DateTime与java.util.Date对象,当前系统TimeMillis转换    
                    DateTime dt6 = new DateTime(new Date());    
                    Date date = dateTime1.toDate();    
                    DateTime dt7 = new DateTime(System.currentTimeMillis());    
                    dateTime1.getMillis();   
                      
                    Calendar calendar = Calendar.getInstance();    
                    dateTime = new DateTime(calendar);  
        }  
    }

 

更多:

https://www.ibm.com/developerworks/cn/java/j-jodatime.html

http://www.jianshu.com/p/efdeda608780

 

 

本文:Java日期简化工具Joda Time

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.