一、背景
jdk 1.8
之前, Java
时间使用java.util.Date
和 java.util.Calendar
类。
Date today = new Date();
System.out.println(today);
// 转为字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String todayStr = sdf.format(today);
System.out.println(todayStr);
Date
的几个问题:
- 如果不格式化,
Date
打印出的日期可读性差; - 可以使用
SimpleDateFormat
对时间进行格式化,但SimpleDateFormat
是线程不安全的(阿里巴巴开发手册中禁用static
修饰SimpleDateFormat
); Date
对时间处理比较麻烦,比如想获取某年、某月、某星期,以及n
天以后的时间,如果用Date
来处理的话真是太难了,并且Date
类的getYear()
、getMonth()
这些方法都被弃用了;
二、JDK 1.8
新的日期时间类型
Java8
引入的新的一系列API
,对时间日期的处理提供了更好的支持,清楚的定义了时间日期的一些概念,比如说,瞬时时间(Instant
),持续时间(duration
),日期(date
),时间(time
),时区(time-zone
)以及时间段(Period
)。
LocalDate
:不包含时间的日期,比如2019-10-14
。可以用来存储生日,周年纪念日,入职日期等。LocalTime
:与LocalDate
想对照,它是不包含日期的时间。LocalDateTime
:包含了日期及时间,没有偏移信息(时区)。ZonedDateTime
:包含时区的完整的日期时间,偏移量是以UTC
/格林威治时间为基准的。Instant
:时间戳,与System.currentTimeMillis()
类似。Duration
:表示一个时间段。Period
:用来表示以年月日来衡量一个时间段。DateTimeFormatter
:新的日期解析格式化类。
2.1 LocalDate
LocalDate
类内只包含日期,不包含具体时间。只需要表示日期而不包含时间,就可以使用它。
public static void localDate() {
//获取当前年月日
LocalDate today = LocalDate.now();
System.out.println("当前年月日:" + today);
// 获取年的两种方式
int thisYear = today.getYear();
int thisYearAnother = today.get(ChronoField.YEAR);
System.out.println("今年是" + thisYear + "年");
System.out.println("今年是" + thisYearAnother + "年");
// 获取月
Month thisMonth = today.getMonth();
System.out.println(thisMonth.toString());
// 这是今年的第几个月(两种写法)
int monthOfYear = today.getMonthValue();
// int monthOfYear = today.get(ChronoField.MONTH_OF_YEAR);
System.out.println("这个月是今年的第" + monthOfYear + "个月");
// 月份的天数
int length = today.lengthOfMonth();
System.out.println(