JDK1.8 新增的日期时间API

JDK1.8 新增的日期时间API

LocalDate、 LocalTime、LocalDateTime类的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。
注: ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法

这些新增的日期时间API都在 java.time包下

获取对象的方法

方式1通过静态方法  now();

例如:LocalDateTime ldt =LocalDateTime.now();

方式2通过静态方法of()方法参数可以指定年月日时分秒

例如:LocalDateTime of =LocalDateTime.of(2018, 12, 30, 20, 20, 20);

常用方法

1.与获取相关的方法:get系类的方法

ldt.getYear();获取年

ldt.getMinute();获取分钟

ldt.getHour();获取小时

getDayOfMonth 获得月份天数(1-31)
getDayOfYear 获得年份天数(1-366)
getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
getMonth 获得月份, 返回一个Month 枚举值
getMonthValue 获得月份(1-12)
getYear 获得年份

2.格式化日期日期字符串的方法 format()

例如:String yyyy = ldt.format(DateTimeFormatter.ofPattern("yyyy"));

3.转换的方法 toLocalDate();toLocalTime();

例如:LocalDate localDate = ldt.toLocalDate();

例如:LocalTime localTime = ldt.toLocalTime();

4.判断的方法

isAfter()判断一个日期是否在指定日期之后

isBefore()判断一个日期是否在指定日期之前

isLeapYear()判断是否是闰年注意是LocalDate类中的方法

例如:  boolean after =ldt.isAfter(LocalDateTime.of(2024, 1, 1, 2, 3));

例如  boolean b=LocalDate.now().isLeapYear();

5.解析的静态方法parse("2007-12-03T10:15:30");

paser() 将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败

例如:LocalDateTime parse = LocalDateTime.parse("2007-12-03T10:15:30");

按照我们指定的格式去解析:

//按照我们指定的格式去解析

注意细节:如果用LocalDateTime 想按照我们的自定义的格式去解析,注意

日期字符串的年月日时分秒要写全,不然就报错

LocalDateTime ldt4 = LocalDateTime.now();

DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

 LocalDateTime.parse("2018-01-21 20:30:36", formatter2);

6.添加年月日时分秒的方法 plus系列的方法 都会返回一个新的LocalDateTime的对象

       LocalDateTime localDateTime = ldt.plusYears(1);

       LocalDateTime localDateTime1 = ldt.plusMonths(3);

       LocalDateTime localDateTime2=ldt.plusHours(10);

7.减去年月日时分秒的方法 minus 系列的方法 注意都会返回一个新的LocalDateTime的对象

例如:LocalDateTime localDateTime2 = ldt.minusYears(8);

8.指定年月日时分秒的方法 with系列的方法

例如 LocalDateTime localDateTime3 = ldt.withYear(1998);

Instant 时间戳类从1970-01-01 00:00:00截止到当前时间的毫秒值

DateTimeFormatter :解析和格式化日期或时间的类

1.  获取对象的方式,通过静态方法ofPattern("yyyy-MM-dd");

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");

       LocalDateTime now = LocalDateTime.now();

2.format()方法把一个日期对象的默认格式 格式化成指定的格式

       String format1 = dateFormat.format(now);

       System.out.println(format1);

3格式化日期 方式2使用日期类中的format方法 传入一个日期格式化类对象

LocalDateTime now1 = LocalDateTime.now();

使用日期类中的format方法 传入一个日期格式化类对象

使用DateTimeFormatter中提供好的日期格式常量

now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

4.使用自定义的日期格式格式化字符串

DateTimeFormatter timeFormat =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//自定义一个日期格式

        String time= now1.format(timeFormat);

       System.out.println(time);

5. 把一个日期字符串转成日期对象

使用日期类中的parse方法传入一个日期字符串,传入对应的日期格式化类

DateTimeFormatter dateFormat =DateTimeFormatter.ofPattern("yyyy-MM-dd");

LocalDateTime parse = LocalDateTime.parse(time,timeFormat);

       System.out.println(parse);

你可能感兴趣的:(Java8)