Java 8 LocalDateTime

操作符 功能
now 获取当前时间
of 获取指定时间
plus 加上指定数量的时间
with 调整时间返回新的副本
adjustInto 调整时间返回新的副本
from 转换TemporalAccessor为LocalDateTime
get 得到LocalDateTime的指定字段的值
range 得到指定时间字段的范围
until 得到相差的时间
  1. now
//获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
  1. of
 //获取指定时间
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
LocalDateTime of2 = LocalDateTime.of(2019, 11, 06, 14, 30,01);
System.out.println(of);
System.out.println(of2);
//  2019-11-06T14:30:01
//  2019-11-06T14:30:01
  1. plus
//时间加上半天
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
LocalDateTime plus = of.plus(1, ChronoUnit.HALF_DAYS);
System.out.println(of);
System.out.println(plus);
// 2019-11-06T14:30:01
// 2019-11-07T02:30:01
  1. with
 //设置分钟数
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
LocalDateTime withMinute = of.withMinute(2);
System.out.println(of);
System.out.println(withMinute);
// 2019-11-06T14:30:01
// 2019-11-06T14:02:01
  1. adjustInto
//adjustInto与with 等价写法,调整时间
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
LocalDateTime now = LocalDateTime.now();
Temporal temporal = now.adjustInto(of);
LocalDateTime with = of.with(now);
System.out.println(of);
System.out.println(temporal);
System.out.println(with);
//        2019-11-06T14:30:01
//        2019-11-06T16:11:49.547
//        2019-11-06T16:11:49.547
  1. from
//转换TemporalAccessor为LocalDateTime
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
LocalDateTime from = of.from(LocalDateTime.now());
System.out.println(of);
System.out.println(from);
//        2019-11-06T14:30:01
//        2019-11-06T16:12:32.591
  1. get
//得到LocalDateTime的指定字段的值,这里获取天数
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
int day = of.get(ChronoField.DAY_OF_MONTH);
System.out.println(of);
System.out.println(day);
//        2019-11-06T14:30:01
//        6
  1. range
//得返回指定时间字段的范围,这里获取一天的时间范围
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
ValueRange range = of.range(ChronoField.HOUR_OF_DAY);
System.out.println(of);
System.out.println(range);
//        2019-11-06T14:30:01
//        0 - 23
  1. until
//返回相差的时间,这里是两个时间相差的分钟数
LocalDateTime of = LocalDateTime.of(2019, Month.NOVEMBER, 06, 14, 30,01);
long until = of.until(LocalDateTime.now(), ChronoUnit.MINUTES);
System.out.println(of);
System.out.println(until);
//        2019-11-06T14:30:01
//        104
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容