Java JDK8新日期时间API(LocalDate、LocalTime、LocalDateTime类)
-
JDK8之前日期时间API存在的问题:
- 可变性:一般需要的日期和时间这样的类应该是不可变的
- 偏移性:Date中的年份是从1900年开始的,而月份都是从0开始的
package www.bh.c.datanewtest; import java.util.Date; public class Test01 { public static void main(String[] args) { Date date = new Date(2020,11,13); System.out.println(date);//Mon Dec 13 00:00:00 CST 3920 } }
package www.bh.c.datanewtest; import java.util.Date; public class Test01 { public static void main(String[] args) { Date date = new Date(2020,11,13); System.out.println(date);//Mon Dec 13 00:00:00 CST 3920 Date date1 = new Date(2020 - 1900, 11 - 1, 13); System.out.println(date1);//Fri Nov 13 00:00:00 CST 2020 } }
- 格式化:格式化只对Date有用,Calendar则不行
- 线程不安全
-
新时间日期API,新的java.time中包含了所有关于本地日期(LocalDate)、(LocalTime)、本地日期时间(LocalDateTime)、时区(ZoneedDateTime)、持续时间(Duration)的类
-
新时间日期API
- java.time - 包含值对象的基础包
- java.time.chrono - 提供对不同的日历系统的访问
- java.time.format - 格式化和解析时间和日期
- java.time.temporal - 包括底层框架和扩展特性
- java.time.zone - 包含时区支持的类
-
LocalDate、LocalTime、LocalDateTime类
- 这三个是比较重要的类,实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间
- LocalDate代表IOS格式(yyyy-MM-dd的日期,可以存储生日、纪念日等日期
- LocalTime表示一个时间,而不是日期
- LocalDateTime表示日期和时间,最常用的类之一
- LocalDate、LocalTime、LocalDateTime类的使用
package www.bh.c.datanewtest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Test02 {
public static void main(String[] args) {
//now():获取当前的日期、时间、日期时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2020-11-13
System.out.println(localTime);//10:30:32.669231100
System.out.println(localDateTime