1.LocalDateTime(第三代日期类)基本介绍
LocalDateTime
是一个不可变的日期时间对象,这个类是不可变的和线程安全的。表示日期时间,通常被视为年 - 月 - 日 - 小时 - 分 - 秒,还可以访问其他日期和时间字段。这是一个value-based类; 在LocalDateTime
实例上使用身份敏感操作(包括引用相等( ==
),标识哈希码或同步)可能会产生不可预测的结果,应该避免使用, 应使用equals
方法进行比较。
因为LocalDateTimejava.time.LocalDateTime中具有private权限所以不能直接访问,要通过now方法返回当前日期的对象。LocalDateTime ldt=LocalDateTime.now();
2.继承关系图表
3.基本方法
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class T{
public static void main(String[] args) {
LocalDateTime d= LocalDateTime.now();
System.out.println(d);
System.out.println("年="+d.getYear());
System.out.println("月="+d.getMonth());//英文
System.out.println("月="+d.getMonthValue());//数字
LocalDateTime d1= LocalDateTime.now();
System.out.println(d.compareTo(d1));//比较日期,由底层代码可知,d<d1就返回-1,d=d1就返回0,d>d1就返回1;
System.out.println(d.equals(d1));//比较日期是不是相等
//对日期进行格式化,可以自己选择格式。(在” “中自己定义格式)
DateTimeFormatter s = DateTimeFormatter.ofPattern("YYYY年MM月dd日 hh:mm:ss");
String str=s.format(d);
System.out.println(str);
System.out.println(d.toString());//获取日期得字符串形式
System.out.println(d.withDayOfMonth(3));//更改日期
System.out.println(d.withYear(2008));//更改年份
System.out.println(d.withMonth(10));//返回此 LocalDateTime的副本,更改月份
}
}
4.compareTo方法的底层代码
public int compareTo(ChronoLocalDateTime<?> other) { if (other instanceof LocalDateTime) { return compareTo0((LocalDateTime) other); } return ChronoLocalDateTime.super.compareTo(other); } private int compareTo0(LocalDateTime other) { int cmp = date.compareTo0(other.toLocalDate()); if (cmp == 0) { cmp = time.compareTo(other.toLocalTime()); } return cmp; }
public LocalDate toLocalDate() { return date; }
int compareTo0(LocalDate otherDate) { int cmp = (year - otherDate.year); if (cmp == 0) { cmp = (month - otherDate.month); if (cmp == 0) { cmp = (day - otherDate.day); } } return cmp; }
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
5.Instant时间戳
可以与date类进行转换
Instant i=Instant.now(); Date d=Date.from(i);//Instant转Date Instant i1=d.toInstant();//Date转Instant
6.进阶方法(plus与minus对日期进行加减)
import java.time.LocalDateTime;
class T{
public static void main(String[] args) {
LocalDateTime ldt=LocalDateTime.now();
System.out.println(ldt.toString());
LocalDateTime L=ldt.plusDays(90);
System.out.println("90天后的日期:"+L.toString());
LocalDateTime L1=ldt.minusMonths(800);
System.out.println("800个月后的日期是:"+L1.toString());
}
}