threeten-extra是一个基于java8的java.time的扩展包,本文简单介绍一下threeten-extra的使用实例。

maven

        <dependency>
            <groupId>org.threeten</groupId>
            <artifactId>threeten-extra</artifactId>
            <version>1.2</version>
        </dependency>

实例

获取日期的年、月、周、天、时、分

LocalDateTime first = LocalDateTime.parse("2017-07-03T10:15:30", DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime second = LocalDateTime.parse("2011-08-08T12:15:10", DateTimeFormatter.ISO_DATE_TIME);
    @Test
    public void testYears(){
        System.out.println(Years.between(first,second));
    }

    @Test
    public void testMonths(){
        System.out.println(Months.between(first,second));
    }

    @Test
    public void testWeeks(){
        System.out.println(Weeks.between(first,second));
    }

    @Test
    public void testDays(){
        System.out.println(Days.between(LocalDate.parse("2017-08-01"),LocalDate.parse("2017-08-03")));
    }

    @Test
    public void testHours(){
        System.out.println(Hours.between(first,second).getAmount());
    }

    @Test
    public void testMinutes(){
        System.out.println(Minutes.between(first,second));
    }

    @Test
    public void testSeconds(){
        System.out.println(Seconds.between(first,second));
    }

获取am或pm时间

    @Test
    public void testAmPm(){
        System.out.println(AmPm.from(LocalTime.now()));
    }

获取月或年中的天数

    @Test
    public void testDayOfMonth(){
        System.out.println(DayOfMonth.from(LocalDate.now()));
    }

    @Test
    public void testDayOfYear(){
        System.out.println(DayOfYear.from(LocalDate.now()));
    }

获取上/下一工作日

    @Test
    public void testTemporals(){
        System.out.println(first.with(Temporals.previousWorkingDay()));
        System.out.println(first.with(Temporals.nextWorkingDay()));
    }

获取时间距离

@Test
    public void testDuration(){
        System.out.println(PeriodDuration.between(first,second).getPeriod());
        System.out.println(PeriodDuration.between(first,second).getDuration());
    }

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...