当前位置: 首页 > news >正文

【Java常用的API】JDK8相关时间类

🍬 博主介绍👨‍🎓 博主介绍:大家好,我是 hacker-routing ,很高兴认识大家~
✨主攻领域:【渗透领域】【应急响应】 【Java】 【VulnHub靶场复现】【面试分析】
🎉点赞➕评论➕收藏 == 养成习惯(一键三连)😋
🎉欢迎关注💗一起学习👍一起讨论⭐️一起进步📝文末有彩蛋
🙏作者水平有限,欢迎各位大佬指点,相互学习进步!

目录

为什么要学JDK8新增时间相关类呢?

JDK8时间类

Zoneld时区

Instant时间戳

ZoneDateTime 带时区的时间

JDK日期格式化类:

DateTimeFormatter 用于时间的格式化和解析

日历类

工具类


为什么要学JDK8新增时间相关类呢?

JDK8时间类

Zoneld时区

代码解释:

package jdk8;import java.time.ZoneId;
import java.util.Set;public class zoneld_demon1 {public static void main(String[] args) {/*static Set<string> getAvailableZoneIds() 获取Java中支持的所有时区static ZoneId systemDefault() 获取系统默认时区static Zoneld of(string zoneld) 获取一个指定时区*///1、获取所有的时区名称Set<String> zoneIds = ZoneId.getAvailableZoneIds();System.out.println(zoneIds.size()); //600System.out.println(zoneIds); //Asia/shanghai//2、获取系统默认时区ZoneId zoneId = ZoneId.systemDefault();System.out.println(zoneId); //Asia/Shanghai//3、获取一个指定时区ZoneId zoneId1 = ZoneId.of("Asia/Pontianak");System.out.println(zoneId1);//Asia/Pontianak}
}

Instant时间戳

package jdk8;import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;public class InstantDemo {public static void main(String[] args) {/*static Instant now() 获取当前时间的Instant对象(标准时间)static Instant ofXxxx(long epochMilli) 根据(秒/毫秒/纳秒)获取Instant对象ZonedDateTime atZone(ZoneIdzone) 指定时区boolean isxxx(Instant otherInstant) 判断系列的方法Instant minusXxx(long millisToSubtract) 减少时间系列的方法Instant plusXxx(long millisToSubtract) 增加时间系列的方法*///1、获取当前时间的Instant对象(标准时间)Instant now = Instant.now();System.out.println(now);System.out.println("-------------------------------");//2、根据(秒/毫秒/纳秒)获取Instant对象Instant instant1 = Instant.ofEpochMilli(1L);System.out.println(instant1);Instant instant2 = Instant.ofEpochSecond(1L);System.out.println(instant2);Instant instant3 = Instant.ofEpochSecond(1L, 9000000000L);System.out.println(instant3);System.out.println("--------------------------------------");//3. 指定时区ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));System.out.println(time);//4.isXxx 判断Instant instant4=Instant.ofEpochMilli(0L);Instant instant5 =Instant.ofEpochMilli(1000L);//5.用于时间的判断//isBefore:判断调用者代表的时间是否在参数表示时间的前面boolean result1=instant4.isBefore(instant5);System.out.println(result1);//true//isAfter:判断调用者代表的时间是否在参数表示时间的后面boolean result2 = instant4.isAfter(instant5);System.out.println(result2);//false//6.Instant minusXxx(long millisToSubtract) 减少时间系列的方法Instant instant6 =Instant.ofEpochMilli(3000L);System.out.println(instant6);//1970-01-01T00:00:03ZInstant instant7 =instant6.minusSeconds(1);System.out.println(instant7);//1970-01-01T00:00:02Z}
}

ZoneDateTime 带时区的时间

代码解释:

package jdk8;import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;public class ZoneDateTimeDemo {public static void main(String[] args) {/*        static ZonedDateTime now() 获取当前时间的ZonedDateTime对象static ZonedDateTime ofXxxx(。。。) 获取指定时间的ZonedDateTime对象ZonedDateTime withXxx(时间) 修改时间系列的方法ZonedDateTime minusXxx(时间) 减少时间系列的方法ZonedDateTime plusXxx(时间) 增加时间系列的方法*///1.获取当前时间对象(带时区)ZonedDateTime now = ZonedDateTime.now();System.out.println(now);//2.获取指定的时间对象(带时区)1/年月日时分秒纳秒方式指定ZonedDateTime time1 = ZonedDateTime.of(2023, 10, 1,11, 12, 12, 0, ZoneId.of("Asia/Shanghai"));System.out.println(time1);//通过Instant + 时区的方式指定获取时间对象Instant instant = Instant.ofEpochMilli(0L);ZoneId zoneId = ZoneId.of("Asia/Shanghai");ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);System.out.println(time2);//3.withXxx 修改时间系列的方法ZonedDateTime time3 = time2.withYear(2000);System.out.println(time3);//4. 减少时间ZonedDateTime time4 = time3.minusYears(1);System.out.println(time4);//5.增加时间ZonedDateTime time5 = time4.plusYears(1);System.out.println(time5);}
}

JDK日期格式化类:

DateTimeFormatter 用于时间的格式化和解析

代码解析:

package jdk8;import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;public class DateTimeForMatterDemo {public static void main(String[] args) {/*static DateTimeFormatter ofPattern(格式) 获取格式对象String format(时间对象) 按照指定方式格式化*///获取时间对象ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));// 解析/格式化器DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a");// 格式化System.out.println(dtf1.format(time));}
}

日历类

package com.itheima.a02jdk8datedemo;import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.MonthDay;public class A05_LocalDateDemo {public static void main(String[] args) {//1.获取当前时间的日历对象(包含 年月日)LocalDate nowDate = LocalDate.now();//System.out.println("今天的日期:" + nowDate);//2.获取指定的时间的日历对象LocalDate ldDate = LocalDate.of(2023, 1, 1);System.out.println("指定日期:" + ldDate);System.out.println("=============================");//3.get系列方法获取日历中的每一个属性值//获取年int year = ldDate.getYear();System.out.println("year: " + year);//获取月//方式一:Month m = ldDate.getMonth();System.out.println(m);System.out.println(m.getValue());//方式二:int month = ldDate.getMonthValue();System.out.println("month: " + month);//获取日int day = ldDate.getDayOfMonth();System.out.println("day:" + day);//获取一年的第几天int dayofYear = ldDate.getDayOfYear();System.out.println("dayOfYear:" + dayofYear);//获取星期DayOfWeek dayOfWeek = ldDate.getDayOfWeek();System.out.println(dayOfWeek);System.out.println(dayOfWeek.getValue());//is开头的方法表示判断System.out.println(ldDate.isBefore(ldDate));System.out.println(ldDate.isAfter(ldDate));//with开头的方法表示修改,只能修改年月日LocalDate withLocalDate = ldDate.withYear(2000);System.out.println(withLocalDate);//minus开头的方法表示减少,只能减少年月日LocalDate minusLocalDate = ldDate.minusYears(1);System.out.println(minusLocalDate);//plus开头的方法表示增加,只能增加年月日LocalDate plusLocalDate = ldDate.plusDays(1);System.out.println(plusLocalDate);//-------------// 判断今天是否是你的生日LocalDate birDate = LocalDate.of(2000, 1, 1);LocalDate nowDate1 = LocalDate.now();MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());MonthDay nowMd = MonthDay.from(nowDate1);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗?}
}
package com.itheima.a02jdk8datedemo;import java.time.LocalTime;public class A06_LocalTimeDemo {public static void main(String[] args) {// 获取本地时间的日历对象。(包含 时分秒)LocalTime nowTime = LocalTime.now();System.out.println("今天的时间:" + nowTime);int hour = nowTime.getHour();//时System.out.println("hour: " + hour);int minute = nowTime.getMinute();//分System.out.println("minute: " + minute);int second = nowTime.getSecond();//秒System.out.println("second:" + second);int nano = nowTime.getNano();//纳秒System.out.println("nano:" + nano);System.out.println("------------------------------------");System.out.println(LocalTime.of(8, 20));//时分System.out.println(LocalTime.of(8, 20, 30));//时分秒System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒LocalTime mTime = LocalTime.of(8, 20, 30, 150);//is系列的方法System.out.println(nowTime.isBefore(mTime));System.out.println(nowTime.isAfter(mTime));//with系列的方法,只能修改时、分、秒System.out.println(nowTime.withHour(10));//plus系列的方法,只能修改时、分、秒System.out.println(nowTime.plusHours(10));}
}
package com.itheima.a02jdk8datedemo;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;public class A07_LocalDateTimeDemo {public static void main(String[] args) {// 当前时间的的日历对象(包含年月日时分秒)LocalDateTime nowDateTime = LocalDateTime.now();System.out.println("今天是:" + nowDateTime);//今天是:System.out.println(nowDateTime.getYear());//年System.out.println(nowDateTime.getMonthValue());//月System.out.println(nowDateTime.getDayOfMonth());//日System.out.println(nowDateTime.getHour());//时System.out.println(nowDateTime.getMinute());//分System.out.println(nowDateTime.getSecond());//秒System.out.println(nowDateTime.getNano());//纳秒// 日:当年的第几天System.out.println("dayofYear:" + nowDateTime.getDayOfYear());//星期System.out.println(nowDateTime.getDayOfWeek());System.out.println(nowDateTime.getDayOfWeek().getValue());//月份System.out.println(nowDateTime.getMonth());System.out.println(nowDateTime.getMonth().getValue());LocalDate ld = nowDateTime.toLocalDate();System.out.println(ld);LocalTime lt = nowDateTime.toLocalTime();System.out.println(lt.getHour());System.out.println(lt.getMinute());System.out.println(lt.getSecond());}
}

工具类

package com.itheima.a02jdk8datedemo;import java.time.LocalDate;
import java.time.Period;public class A08_PeriodDemo {public static void main(String[] args) {// 当前本地 年月日LocalDate today = LocalDate.now();System.out.println(today);// 生日的 年月日LocalDate birthDate = LocalDate.of(2000, 1, 1);System.out.println(birthDate);Period period = Period.between(birthDate, today);//第二个参数减第一个参数System.out.println("相差的时间间隔对象:" + period);System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());System.out.println(period.toTotalMonths());}
}
package com.itheima.a02jdk8datedemo;import java.time.Duration;
import java.time.LocalDateTime;public class A09_DurationDemo {public static void main(String[] args) {// 本地日期时间对象。LocalDateTime today = LocalDateTime.now();System.out.println(today);// 出生的日期时间对象LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);System.out.println(birthDate);Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数System.out.println("相差的时间间隔对象:" + duration);System.out.println("============================================");System.out.println(duration.toDays());//两个时间差的天数System.out.println(duration.toHours());//两个时间差的小时数System.out.println(duration.toMinutes());//两个时间差的分钟数System.out.println(duration.toMillis());//两个时间差的毫秒数System.out.println(duration.toNanos());//两个时间差的纳秒数}
}
package com.itheima.a02jdk8datedemo;import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;public class A10_ChronoUnitDemo {public static void main(String[] args) {// 当前时间LocalDateTime today = LocalDateTime.now();System.out.println(today);// 生日时间LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,0, 0, 0);System.out.println(birthDate);System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));}
}

相关文章:

  • linux离线安装maven
  • P1629 邮递员送信
  • 蓝桥杯 本质上升序列
  • 2024批量下载微博内容点赞转发评论数等数据,词云分析微博数据
  • 【动手学深度学习-pytorch】9.2长短期记忆网络(LSTM)
  • K8S的mountPath和subPath
  • LeetCode 206.反转链表
  • 如何在智能交通系统中使用物联网技术提高道路安全和效率
  • 怎么让ChatGPT批量写作原创文章
  • Springboot+MybatisPlus+EasyExcel实现文件导入数据
  • Mysql中的那些锁
  • 【跟着CHATGPT学习硬件外设 | 04】ADC
  • SVG XML 格式定义图形入门介绍
  • 【AI模型-机器学习工具部署】远程服务器配置Jupyter notebook或jupyter lab服务
  • kubernetes-k9s一个基于Linux 终端的集群管理工具
  • docker python 配置
  • Druid 在有赞的实践
  • java第三方包学习之lombok
  • maven工程打包jar以及java jar命令的classpath使用
  • mongodb--安装和初步使用教程
  • MySQL-事务管理(基础)
  • Python连接Oracle
  • Vue小说阅读器(仿追书神器)
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 基于遗传算法的优化问题求解
  • 码农张的Bug人生 - 初来乍到
  • 设计模式走一遍---观察者模式
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 在Unity中实现一个简单的消息管理器
  • 摩拜创始人胡玮炜也彻底离开了,共享单车行业还有未来吗? ...
  • (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (pytorch进阶之路)扩散概率模型
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (第二周)效能测试
  • (论文阅读22/100)Learning a Deep Compact Image Representation for Visual Tracking
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (算法)Game
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET gRPC 和RESTful简单对比
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .NET WebClient 类下载部分文件会错误?可能是解压缩的锅
  • .NET 回调、接口回调、 委托
  • .net分布式压力测试工具(Beetle.DT)
  • .NET中统一的存储过程调用方法(收藏)
  • @Repository 注解
  • [ IO.File ] FileSystemWatcher
  • [acm算法学习] 后缀数组SA
  • [Bzoj4722]由乃(线段树好题)(倍增处理模数小快速幂)
  • [ERROR] Plugin 'InnoDB' init function returned error
  • [HDOJ4911]Inversion
  • [Intel Edison开发板] 05、Edison开发基于MRAA实现IO控制,特别是UART通信
  • [LeetCode] Longest Common Prefix 字符串公有前序
  • [Linux] Apache的配置与运用
  • [Linux](15)线程基础,线程控制,线程的互斥与同步