1.第三代日期类
前面两代日期类的不足分析
JDK 1.0中包含了一个java.uti.Date类,但是它的大多数方法已经在JDK1.1引Calendar类之后被弃用了。
而Calendar也存在问题是:
- 可变性:像日期和时间这样的类应该是不可变的
- 偏移性:Date中的年份是从1900开始的,而月份都从0开始
- 格式化:格式化只对Date有用,Calendar则不行
- 此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)
第三代日期类常见方法(JDK8加入)
- LocalDate(日期/年月日)LocalTime(时间/时分秒)LocalDateTime(日期时间/年月日时分秒)
- DateTimeFormatter 格式日期类 类似于 SimpleDateFormat DateTimeFormat dtf = DateTimeFormatter.ofPattern(格式);String str = dtf.format(日期对象);
- Instant 时间戳 类似于Date 提供了一系列和Date类转换的方式 Instant-->Date: Date date = Date.from(instant); Date->Instant:Instant instant = date.tolnstant();
- 第三代日期类更多方法 LocalDateTime类 MonthDay类:检查重复事件 是否是闻年 增加日期的某个部分使用plus方法测试增加时间的某个部分 使用minus方法测试查着一年前和一年后的日期
其他不再列出 用的时候查看API即可
package com.logic.date_;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;public class LocalDate_ {public static void main(String[] args) {//第三代日期//1. 使用now() 返回表示当前日期时间的 对象LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()System.out.println(ldt);//2. 使用DateTimeFormatter 对象来进行格式化// 创建 DateTimeFormatter对象DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String format = dateTimeFormatter.format(ldt);System.out.println("格式化的日期=" + format);System.out.println("年=" + ldt.getYear());System.out.println("月=" + ldt.getMonth());System.out.println("月=" + ldt.getMonthValue());System.out.println("日=" + ldt.getDayOfMonth());System.out.println("时=" + ldt.getHour());System.out.println("分=" + ldt.getMinute());System.out.println("秒=" + ldt.getSecond());LocalDate now = LocalDate.now(); //可以获取年月日LocalTime now2 = LocalTime.now();//获取到时分秒//提供 plus 和 minus方法可以对当前时间进行加或者减//看看890天后,是什么时候 把 年月日-时分秒LocalDateTime localDateTime = ldt.plusDays(890);System.out.println("890天后=" + dateTimeFormatter.format(localDateTime));//看看在 3456分钟前是什么时候,把 年月日-时分秒输出LocalDateTime localDateTime2 = ldt.minusMinutes(3456);System.out.println("3456分钟前 日期=" + dateTimeFormatter.format(localDateTime2));}
}
package com.logic.date_;import java.time.Instant;
import java.util.Date;public class Instant_ {public static void main(String[] args) {Instant instant = Instant.now();System.out.println(instant);Date date = Date.from(instant);System.out.println(date);Instant instant2 = date.toInstant();System.out.println(instant2);}
}