千家信息网

java8中LocalDateTime的作用是什么

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,java8中LocalDateTime的作用是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。2. 关于LocalDa
千家信息网最后更新 2025年02月05日java8中LocalDateTime的作用是什么

java8中LocalDateTime的作用是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

2. 关于LocalDateTime的简单介绍

Java的Date,Calendar类型使用起来并不是很方便,而且Date类(据说)有着线程不安全等诸多弊端。同时若不进行封装,会在每次使用时特别麻烦。于是Java8推出了线程安全、简易、高可靠的时间包。并且数据库中也支持LocalDateTime类型,在数据存储时候使时间变得简单。Java8这次新推出的包括三个相关的时间类型:LocalDateTime年月日十分秒;LocalDate日期;LocalTime时间;三个包的方法都差不多。

3. LocalDateTime的简单日常使用

①. 与字符串互相转换

都知道以前对Date进行格式化还要借助SimpDateFormart对象。操作起来不能说麻烦,但也不是那么顺手。下面贴代码LocalDateTime与字符串操作

//将当前时间格式化为字符串 pattern为yyyy-MM等LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));//将时间字符串转换为LocalDateTime LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
②. 获取两时间段相隔(天,小时...)数
Duration duration = Duration.between(startLocalDateTime,endLocalDateTime);//获取相隔天数duration.toDays();//获取相隔小时duration.toHours();//获取相隔分钟duration.toMinutes();//获取相隔秒数uration.getSeconds()//获取相隔毫秒duration.toMillis();Period period = Period.between(startLocalDateTime.toLocalDate(),endLocalDateTime.toLocalDate());//获取相隔年period.getYears();//获取相隔月period.getMonths();period.toTotalMonths();
③. 进行时间的加减
//增加plusXX  如:增加一个月LocalDateTime.now().plusMonths(1);//减少minusXX 如:减少一个月LocalDateTime.now().minusMonths(1);
④. 获取当月最后一天
LocalDateTime endLocalDateTime = now.with(TemporalAdjusters.lastDayOfMonth());
⑤. LocalDateTime与Date互转
//LocalDateTime to Date//ZoneId为时区 这里获取系统默认时区ZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.now();//Instant是一个精确到纳秒的时间对象Instant instant = localDateTime.atZone(zone).toInstant();Date date = Date.from(instant);//Date to LocalDateTimeDate date = new Date();Instant instant = date.toInstant();ZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

0