jdk1.8 新特性 Date-LocalTime 和 LocalDateTime

698 阅读2分钟

「这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战

LocalTime

创建对象和localDate类似

LocalTime time = LocalTime.now();    // 14:59:51.86

image.png

上面三个of根据需要指定创建时间

LocalTime of = LocalTime.of(14, 59, 51, 333);    //14:59:51.000000333
LocalTime of1 = LocalTime.of(14, 59, 51);     // 14:59:51  

增加/减少

  • plusHours
  • plusMinutes
  • plusSeconds
  • plusNanos

比较

compareTo() 大于返回1,小于返回-1.相等返回0

				LocalTime of = LocalTime.of(14, 59, 51, 333);    //14:59:51.000000333
				LocalTime of1 = LocalTime.of(14, 59, 51);     // 14:59:51  
				
        int i3 = of.compareTo(of1);   // 1

// 源码
public int compareTo(LocalTime other) {
        int cmp = Integer.compare(hour, other.hour);
        if (cmp == 0) {
            cmp = Integer.compare(minute, other.minute);
            if (cmp == 0) {
                cmp = Integer.compare(second, other.second);
                if (cmp == 0) {
                    cmp = Integer.compare(nano, other.nano);
                }
            }
        }
        return cmp;
    }

LocalDateTime

创建

now() 创建当前时间的对象,日期和时间之间通过T连接

LocalDateTime dateTime = LocalDateTime.now();  //2021-11-09T09:22:05.526

of() 手动构造

image.png

1.手动指定年月日时分秒.当后面的参数缺省时,就会置为0

// 2021-11-11T11:11:11
LocalDateTime of2 = LocalDateTime.of(2021, 11, 11, 11, 11, 11);  

2.参数为LocalDate和LocalTime.将两者拼接成LocalDateTime

//   time : 16:02:30.375
//   localDate : 2021-12-08
LocalDateTime of3 = LocalDateTime.of(localDate, time);  //2021-12-08T16:02:30.375

转换成其他两个类

LocalDateTime 中有两个属性datetime,分别存储日期和时间.因此转换过来和转换成其他两个类特别方便

		private final LocalDate date;
    private final LocalTime time;

toLocalDate() 直接返回date属性

LocalDate localDate2 = of3.toLocalDate();

toLocalTime() 直接返回time属性

LocalTime localTime = of3.toLocalTime();

获取

因为有两个属性,因此LocalDate和LocalTime的

parse解析

可以直接将字符串转换成对应的Local类.

1.使用默认的解析格式,只需要带入时间的字符串即可

	
				LocalDate parse = LocalDate.parse("2021-08-09");
        LocalTime parse1 = LocalTime.parse("23:59:59");
				LocalDateTime parse2 = LocalDateTime.parse("2021-08-09T23:59:59");

			

源码:

// parse的formatter就是下面的DateTimeFormatter
public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {
        Objects.requireNonNull(formatter, "formatter");
        return formatter.parse(text, LocalDateTime::from);
    }

// dateTtime 中间使用T而不是空格拼接
public static final DateTimeFormatter ISO_LOCAL_DATE_TIME;
    static {
        ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE)
                .appendLiteral('T')
                .append(ISO_LOCAL_TIME)
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }