Joda对时间的操作

Joda-Time:专门处理日期时间的库

使用

(1)导入maven

        
            joda-time
            joda-time
            2.9.9
        

(2)事例

public class JodaTest {
    @Test
    public void fun1() {
        DateTime time = new DateTime();
        //格式化字符串
        String time1 = time.toString("yyyy-MM-dd HH:mm:ss EE");
        System.out.println("*******   time1 : " + time1);

        //转换为Date
        Date time2 = time.toDate();
        System.out.println("time2 : "+ time2);

        //时间解析
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTime d = DateTime.parse("2017-10-17 20:06:05", format);
        System.out.println("*******   d : " + d);

        //增加、减少日期(数值为负就是减少日期)
        DateTime dateTime1 = DateTime.parse("2012-12-03");
        System.out.println("*******   30 : " + dateTime1.plusDays(30));
        System.out.println("*******   3 : " + dateTime1.plusHours(3));
        System.out.println("*******   3 : " + dateTime1.plusMinutes(3));
        System.out.println("*******   2 : " + dateTime1.plusMonths(2));
        System.out.println("*******   4 : " + dateTime1.plusSeconds(4));
        System.out.println("*******   2 : " + dateTime1.plusWeeks(5));
        System.out.println("*******   4 : " + dateTime1.plusYears(3));

        //判断是否闰月
        boolean leap = new DateTime().monthOfYear().isLeap();
        System.out.println(leap);

        //得到某一日期的年与日时分秒
        DateTime t = new DateTime();
        System.out.println("******* 年 : " + time.getYear());
        System.out.println("******* 月 : " + time.getMonthOfYear());
        System.out.println("******* 日 : " + time.getDayOfMonth());
        System.out.println("******* 时 : " + time.getHourOfDay());
        System.out.println("******* 分 : " + time.getMinuteOfHour());
        System.out.println("******* 秒 : " + time.getSecondOfMinute());

        //获得两个时间相差的年、月、日、时、分、秒
        LocalDate start = new LocalDate(new DateTime("2017-02-02"));
        LocalDate end = new LocalDate(new DateTime("2017-03-02"));
        int years = Years.yearsBetween(start, end).getYears(); //相差多少年
        int months = Months.monthsBetween(start, end).getMonths(); //相差多少月
        int days = Days.daysBetween(start, end).getDays(); //相差多少日
        int hours = Hours.hoursBetween(start, end).getHours(); //相差多少日
        int minutes = Minutes.minutesBetween(start, end).getMinutes(); //相差多少分
        int seconds = Seconds.secondsBetween(start, end).getSeconds(); //相差多少秒
        System.out.println(years+" "+months+" "+days+" "+hours+" "+minutes+" "+seconds);

        //获取18天之后的某天在下个月的当前周的第一天/最后一天日期
        String t1 = new DateTime().plusDays(18).plusMonths(1).dayOfWeek().withMinimumValue().toString("yyyy-MM-dd HH:mm:ss");
        System.out.println(t1);
        String t2 = new DateTime().plusDays(18).plusMonths(1).dayOfWeek().withMaximumValue().toString("yyyy-MM-dd HH:mm:ss");
        System.out.println(t2);

    }
}

输出结果

Joda对时间的操作_第1张图片

 

你可能感兴趣的:(Java)