Java8 日期时间API

一、基本知识

使用Java8,新的日期时间API引入覆盖旧的日期时间API的以下缺点:

  • 非线程安全 - java.util.Date不是线程安全的,因此开发者必须在使用日期处理并发性问题。新的日期时间API是不可变的,并且没有setter方法。
  • 设计不佳 - 默认的开始日期从1900年,开始每月从1天从0开始,所以没有统一。不直接使用方法操作日期。新的API提供了这样操作实用方法。
  • 困难的时区处理 - 开发人员必须编写大量的代码来处理时区的问题。新的API设计开发保持特定领域设计。

Java8引入了java.time包 - 下一个新的日期时间API。

  • 本地 - 简化日期时间API,没有时间处理区的复杂性。
  • 时区 - 专业的日期时间API来处理各种时区。
二、 Java8 本地DateTime API

测试类:

/**
 * Java8 本地DateTime API
 *
 * @author Kevin
 * @date 2017-01-28
 */
public class DateTimeTest {

    public static void main(String[] args) {
        // LocalDate/本地时间和LocalDateTime类简化时区不需要开发。
        LocalDateTime currentTime = LocalDateTime.now();
        System.out.println("Current DateTime: " + currentTime);

        LocalDate date1 = currentTime.toLocalDate();
        System.out.println("date1: " + date1);

        Month month = currentTime.getMonth();
        int day = currentTime.getDayOfMonth();
        int seconds = currentTime.getSecond();
        System.out.println("Month: " + month
                + " day: " + day
                + " seconds: " + seconds
        );

        LocalDateTime date2 = currentTime.withDayOfMonth(28).withYear(2020);
        System.out.println("date2: " + date2);

        LocalDate date3 = LocalDate.of(2018, Month.JANUARY, 28);
        System.out.println("date3: " + date3);

        LocalTime date4 = LocalTime.of(22, 28);
        System.out.println("date4: " + date4);

        LocalTime date5 = LocalTime.parse("22:28:30");
        System.out.println("date5: " + date5);
    }

}

运行结果:

Current DateTime: 2017-01-28T22:30:45.536
date1: 2017-01-28
Month: JANUARY day: 28 seconds: 45
date2: 2020-01-28T22:30:45.536
date3: 2018-01-28
date4: 22:28
date5: 22:28:30
三、Java8 时区DateTime API

测试类:

/**
 * Java8 时区DateTime API 测试
 *
 * @author Kevin
 * @date 2017-01-28
 */
public class ZonedDateTimeTest {

    public static void main(String[] args) {
        ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
        System.out.println("currentZonedDateTime: " + currentZonedDateTime);

        ZoneId id = ZoneId.of("Europe/Paris");
        System.out.println("ZoneId: " + id);

        ZoneId currentZone = ZoneId.systemDefault();
        System.out.println("CurrentZone: " + currentZone);
    }

}

运行结果:

currentZonedDateTime: 2017-01-28T22:36:22.280+08:00[Asia/Shanghai]
ZoneId: Europe/Paris
CurrentZone: Asia/Shanghai
四、Java8 ChronoUnits枚举

测试类:

/**
 * Java8 ChronoUnits枚举 测试
 *
 * @author Kevin
 * @date 2017-01-28
 */
public class ChronoUnitsTest {

    public static void main(String[] args) {
        // java.time.temporal.ChronoUnit 枚举在Java8中添加,以取代旧的API用来代表日,月等整数值.
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + currentDate);

        LocalDate nextWeek = currentDate.plus(1, ChronoUnit.WEEKS);
        System.out.println("Next week: " + nextWeek);

        LocalDate nextMonth = currentDate.plus(1, ChronoUnit.MONTHS);
        System.out.println("Next month: " + nextMonth);

        LocalDate nextYear = currentDate.plus(1, ChronoUnit.YEARS);
        System.out.println("Next year: " + nextYear);

        LocalDate nextDecade = currentDate.plus(1, ChronoUnit.DECADES);
        System.out.println("Date after ten year: " + nextDecade);
    }

}

运行结果:

Current date: 2017-01-28
Next week: 2017-02-04
Next month: 2017-02-28
Next year: 2018-01-28
Date after ten year: 2027-01-28
五、Java8 期间及持续时间

使用Java8,两个专门类引入来处理时间差。

  • Period - 处理有关基于时间的日期数量。
  • Duration - 处理有关基于时间的时间量。

测试类:

/**
 * Java8 期间及持续时间 测试
 *
 * @author Kevin
 * @date 2017-01-29
 */
public class PeriodTest {

    public static void main(String args[]) {
        // 处理有关基于时间的日期数量
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + currentDate);

        LocalDate nextMonthDate = currentDate.plus(1, ChronoUnit.MONTHS);
        System.out.println("Next month: " + nextMonthDate);

        Period period = Period.between(currentDate, nextMonthDate);
        System.out.println("Period: " + period);

        // 处理有关基于时间的时间量
        LocalTime currentTime = LocalTime.now();
        System.out.println("Current time: " + currentTime);

        Duration twoHours = Duration.ofHours(2);
        LocalTime nextTime = currentTime.plus(twoHours);
        System.out.println("Next time: " + nextTime);

        Duration duration = Duration.between(currentTime, nextTime);
        System.out.println("Duration: " + duration);
    }

}

运行结果:

Current date: 2017-01-29
Next month: 2017-02-28
Period: P30D
Current time: 16:09:17.382
Next time: 18:09:17.382
Duration: PT2H

####六、Java8 时间调节器 **TemporalAdjuster 是做日期数学计算。**例如,要获得“本月第二个星期六”或“下周日”。

测试类:

/**
 * Java8 时间调节器
 *
 * @author Kevin
 * @date 2017-01-29
 */
public class TemporalAdjusterTest {

    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + currentDate);

        LocalDate nextSunday = currentDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println("Next Sunday on : " + nextSunday);

        LocalDate firstInYear = LocalDate.of(currentDate.getYear(), currentDate.getMonth(), 1);
        LocalDate secondSaturday = firstInYear.with(
                TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(
                TemporalAdjusters.next(DayOfWeek.SATURDAY));
        System.out.println("Second saturday on : " + secondSaturday);
    }

}

运行结果:

Current date: 2017-01-29
Next Sunday on : 2017-02-05
Second saturday on : 2017-01-14
七、Java8 向后兼容

toInstant()方法被添加到可用于将它们转换到新的日期时间的API原始日期和日历对象。使用ofInstant(Insant,ZoneId)方法得到一个LocalDateTime或ZonedDateTime对象。

测试类:

/**
 * Java8 向后兼容
 *
 * @author Kevin
 * @date 2017-01-29
 */
public class InstantTest {

    public static void main(String args[]) {
        Date currentDate = new Date();
        System.out.println("Current date: " + currentDate);

        Instant now = currentDate.toInstant();
        ZoneId currentZone = ZoneId.systemDefault();

        LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
        System.out.println("Local date: " + localDateTime);

        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
        System.out.println("Zoned date: " + zonedDateTime);
    }

}

运行结果:

Current date: Sun Jan 29 16:39:32 CST 2017
Local date: 2017-01-29T16:39:32.091
Zoned date: 2017-01-29T16:39:32.091+08:00[Asia/Shanghai]

####八、参考文章 1.Java8 日期时间API(http://www.yiibai.com/java8/java8_datetime_api.html)

转载于:https://my.oschina.net/zhaokaiju/blog/830655

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值