JDK8中新日期时间API

第三次引入的API是成功的,并且Java 8中引入的java.time API已经纠正了过去的缺陷,将来很长一段时间内它都会为我们服务。
Java8吸收了Joda-Time的精华,以一个新的开始为Java创建优秀的API。新的 java.time 中包含了所有关于本地日期(LocaIDate)、本地时间
(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime和持续时间(Duration)的类。历史悠久的 Date类新增了tolnstant()方法,用于把 Date转换成新的表示形式。这些新增的本地化时间日期API大大简化了日期时间和本地化的管理。

 新时间日期API
java.time-包含值对象的基础包
java.time.chrono-提供对不同的日历系统的访问
java.time.format-格式化和解析时间和日期
java.time.temporal-包括底层框架和扩展特性
java.time.zone -包含时区支持的类
说明:大多数开发者只会用到基础包和format包,也可能会用到temporal包。因此,尽管有68个新的公开类型,大多数开发者,大概将只会用到其中的三分之一。

代码如下:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

public class StartApplication {
    public static void main(String[] args) {
        //时间的偏移量
        Date date = new Date(2022, 5, 10);
        Date date1 = new Date(2022 - 1900, 5 - 1, 10);
        System.out.println(date);
        System.out.println(date1);


        //LocalDate、LocalTime、LocalDateTime
        //now()获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);
        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        //of:设定指定的年、月、日、时、分、秒没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2022, 5, 10, 15, 12, 56);
        System.out.println(localDateTime1);

        //getXxx
        System.out.println(localDateTime1.getYear());
        System.out.println(localDateTime1.getMonth());
        System.out.println(localDateTime1.getMonthValue());
        System.out.println(localDateTime1.getMinute());
        System.out.println(localDateTime1.getDayOfWeek());

        //体现不可变性
        //withXxx设置时间
        LocalDateTime localDateTime2 = localDateTime1.withDayOfMonth(22);
        System.out.println(localDateTime2);
        System.out.println(localDateTime1);

        LocalDateTime localDateTime3 = localDateTime1.plusMonths(3);
        System.out.println(localDateTime3);
        System.out.println(localDateTime1);

        LocalDateTime localDateTime4 = localDateTime1.minusDays(6);
        System.out.println(localDateTime4);
        System.out.println(localDateTime1);
    }
}

结果:

Sat Jun 10 00:00:00 CST 3922
Tue May 10 00:00:00 CST 2022
2022-05-10
15:26:36.834
2022-05-10T15:26:36.834
2022-05-10T15:12:56
2022
MAY
5
12
TUESDAY
2022-05-22T15:12:56
2022-05-10T15:12:56
2022-08-10T15:12:56
2022-05-10T15:12:56
2022-05-04T15:12:56
2022-05-10T15:12:56

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值