JDK8——新增时间类、有关时间数据的交互问题

news2025/6/20 20:13:47

目录

一、实体类

二、数据库

三、数据交换 

四、关于LocalDateTime类型 (java 8)

4.1 旧版本日期时间问题

4.2 新版日期时间API介绍

4.2.1 LocalDate、LocalTime、LocalDateTime

4.2.2 日期时间的修改与比较

4.2.3 格式化和解析操作

4.2.4  Instant: 时间戳

4.2.5  Duration 与 Period——计算时间差

4.2.6 TemporalAdjuster—— 时间校正器

4.2.7 ZonedDateTime 时区讲解


一、实体类

   我们这个实体类中的两个时间类型的数据为LocalDateTime

package com.reggie_take_out.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 员工实体类
 */
@Data
@TableName("Employee")
public class Employee implements Serializable {
//  凡是一个类实现了Serializable接口,建议提供一个固定不变的序列化版本号,这样即使代码修改,java虚拟机也认为是同一个类
    private static final long serialVersionUID = 1L;


    @TableId("id")
    private Long id;

    @TableField("username")
    private String username;

    @TableField("name")
    private String name;

    @TableField("password")
    private String password;

    @TableField("phone")
    private String phone;

    @TableField("sex")
    private String sex;

    @TableField("id_number")
    private String idNumber;

    @TableField("status")
    private Integer status;

    @TableField("create_time")
    private LocalDateTime createTime;

    @TableField("update_time")
    private LocalDateTime updateTime;

    @TableField(value = "create_user",fill = FieldFill.INSERT)
    private Long createUser;

    @TableField(value = "update_user",fill = FieldFill.INSERT_UPDATE)
    private Long updateUser;

}

二、数据库

 

三、数据交换 

LocalDateTime.now()  获取当前时间,格式为: - 月 - 日 - 时 - 分 - 秒

    @Override
    public R saveEmployee(HttpServletRequest request,Employee employee) {
//      首先判断是否存在这个username


//      1. 设置初始密码进行加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//      2. 获取当前操作的用户ID
        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setStatus(1);  入库默认1
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeMapper.insert(employee);

        return R.success("新增员工成功");
    }

四、关于LocalDateTime类型 (java 8)

与日期类进行对比

  JavaSE——java.util.Date日期类演示以及常用方法与操作_我爱布朗熊的博客-CSDN博客

 在前后端交互的时候,前端往往向后端传输字符串

4.1 旧版本日期时间问题

   旧版本中对日期的设计是非常差的

  •    第一条:设计不合理

          看下面的红框,Date类在java.util 与 java.sql中都有 

         java.util.Date同时包含日期和时间的,而java.sql.Date仅仅包含日期。

        此外用于格式化和解析的类在java,text包下

  •  第二条:  日期格式化使用并不是很便捷
    @Test
    void test01() throws ParseException {
//      时间转换成字符串
        Date date = new Date();  //Sun Apr 09 14:03:41 CST 2023
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = sdf.format(date);
        System.out.println(dateTime);   //2023-04-09

//      字符串转换成时间
        Date parse = sdf.parse("2021-05-06");
        System.out.println(parse);  //Thu May 06 00:00:00 CST 2021

    }

  •  第三条: 数据安全问题——非线程安全 

         所有的日期类都是可变的,这是java日期类最大的问题之一

        在多线程的情况下,通过格式化对数据做操作的时候,会存在数据安全问题。

        时间格式化和解析操作是线程不安全的

  •  第四条: 时区处理麻烦

       日期类并不提供国际化,没有时区支持

4.2 新版日期时间API介绍

此套API设计合理,是线程安全的。新的日期及时间API位于java.time包中,下面是一些关键类。

4.2.1 LocalDate、LocalTime、LocalDateTime

  •    LocalDate: 表示日期,包含年月日,格式为 2019-10-16
//      1. 获取指定日期
        LocalDate date = LocalDate.of(2021, 05, 06);
        System.out.println(date);             // 2021-05-06

//      2. 获取当前日期
        LocalDate now = LocalDate.now();
        System.out.println(now);  //2023-04-09

//      3.根据LocalDate对象获取对应信息
        System.out.println("年"+now.getYear());  //2023
        System.out.println("月"+now.getMonth()); //APRIL   这是一个枚举类型
        System.out.println("日"+now.getDayOfMonth()); //9
        System.out.println("星期"+now.getDayOfWeek()); //SUNDAY   这是一个枚举
//      枚举
        System.out.println("月"+now.getMonth().getValue()); //4    枚举值
        System.out.println("星期"+now.getDayOfWeek().getValue()); //7  枚举值

  •    LocalTime: 表示时间,包含时分秒,格式为 16:38:54.158549300
//        1.得到指定时间
        LocalTime time = LocalTime.of(5,23,33,123456);
        System.out.println(time); //05:23:33.000123456

//        2.获取当前时间
        LocalTime now = LocalTime.now();
        System.out.println(now); //分钟:45
        System.out.println("小时:"+now.getHour());   //小时:14
        System.out.println("分钟:"+now.getMinute()); //分钟:45
        System.out.println("秒:"+now.getSecond());   //秒:20
        System.out.println("纳秒:"+now.getNano());   //纳秒:698000000

  •    LocalDateTime: 表示日期时间,包含年月日,时分秒,格式为 2018-09-06T15:33:56.750。
//      1.获取指定的日期时间
        LocalDateTime time = LocalDateTime.of(2023, 04, 05, 12, 15, 30);
        System.out.println(time);

//      2. 获取当前的日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("年"+now.getYear());  //2023
        System.out.println("月"+now.getMonth()); //APRIL   这是一个枚举类型
        System.out.println("日"+now.getDayOfMonth()); //9
        System.out.println("星期"+now.getDayOfWeek()); //SUNDAY   这是一个枚举

        System.out.println("小时:"+now.getHour());   //小时:49
        System.out.println("分钟:"+now.getMinute()); //分钟:45
        System.out.println("秒:"+now.getSecond());   //秒:49
        System.out.println("纳秒:"+now.getNano());   //纳秒:667000000
        

4.2.2 日期时间的修改与比较

  日期的修改:

        LocalDateTime now = LocalDateTime.now();
        System.out.println("now=" + now);   //2023-04-09T14:57:07.994
//      1. 修改年份
//        注意!!
//         并不会修改原来的信息,而是创建一个新的对象
        LocalDateTime localDateTime = now.withYear(1998);
        System.out.println(localDateTime);  //1998-04-09T14:57:07.994


//      2. 在当前日期的基础上加上/减去指定的时间
        System.out.println(now.plusDays(2));  //两天后 2023-04-11T15:03:39.882
        System.out.println(now.plusYears(10));//十年后 2033-04-09T15:03:39.882

        System.out.println(now.minusMonths(6)); //半年后 2022-10-09T15:05:19.798
        System.out.println(now.minusDays(10)); //十天前  2023-03-30T15:05:19.798

日期的比较:

        LocalDate now =LocalDate.now();
        LocalDate date = LocalDate.of(2020,1,3);
//      时间比较
        System.out.println(now.isAfter(date));  //true
        System.out.println(now.isBefore(date)); //false
        System.out.println(now.isEqual(date));  //false

4.2.3 格式化和解析操作

  •    DateTimeFormatter: 日期时间格式化类
        LocalDateTime now = LocalDateTime.now();
//      指定格式
//      1.默认格式 DateTimeFormatter.ISO_LOCAL_DATE_TIME
        DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//      将日期时间转换为字符串
        String format = now.format(isoLocalDateTime);
        System.out.println(format); //默认格式 2023-04-09T15:30:56.136

//      2.ofPattern指定格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format1 = now.format(dateTimeFormatter);
        System.out.println(format1);  //2023-04-09 15:33:01

//      3.将字符串解析为日期时间类型
        LocalDateTime parse = LocalDateTime.parse("1997-05-06 22:45:16", dateTimeFormatter);
        System.out.println(parse);   //1997-05-06T22:45:16

4.2.4  Instant: 时间戳

  •    Instant: 时间戳,表示一个特定的时间瞬间

      在jdk8中给我们新增一个Instant类(时间戳/时间线),内部保存了从1970年1月1日0时0分0秒以来的秒和纳秒(可以精确到纳秒)

        Instant now = Instant.now();
        System.out.println("now= "+now); //2023-04-09T07:40:59.610Z

        System.out.println(now.getNano()); //纳秒数据  610000000

4.2.5  Duration 与 Period——计算时间差

  •    Duration: 用于计算2个时间(LocalTime,时分秒)的距离。

               计算时,后面的数据减去前面的数据

        LocalTime now = LocalTime.now();
        LocalTime time = LocalTime.of(22,48);
//      计算时间差
        System.out.println(now);  //15:50:08.633
        Duration duration = Duration.between(now, time);
//      所差的天数
        System.out.println(duration.toDays());   //0
//      所差小时
        System.out.println(duration.toHours());  //6
//      所差分钟
        System.out.println(duration.toMinutes());//417
//      所差毫秒
        System.out.println(duration.toMillis()); //25071367

  •    Period:    用于计算2个日期(LocalDate,年月日)的距离
        LocalDate now = LocalDate.now();
        LocalDate time = LocalDate.of(1997,12,5);
//      计算时间差
        System.out.println(now);  //2023-04-09
        Period period = Period.between(now, time);
//      所差的年数
        System.out.println(period.getYears());   //-25
//      所差月份
        System.out.println(period.getMonths());  //-4
//      所差天数
        System.out.println(period.getDays());//-4

4.2.6 TemporalAdjuster—— 时间校正器

   有时候我们可以需要如下调整: 将日期调整到"下个月的第一天"等操作。当然我们也可以通过with进行修改,但是通过时间校正器更好。

   通过源码我们发现TemporalAdjuster是一个函数式接口,而且返回值类型和参数列表都是

Temporal类型

        LocalDateTime now = LocalDateTime.now();
//      TemporalAdjuster 函数式接口
//      将当前日期调整到下个月一号
        TemporalAdjuster adjuster =(temporal -> {
//         这个能强制类型转换是因为LocalDateTime实现了Temporal接口
           LocalDateTime dateTIme = (LocalDateTime) temporal;
            LocalDateTime nextMonth = dateTIme.plusMonths(1) //下一个月
                    .withDayOfMonth(1);// 1号
            System.out.println("nextMonth="+nextMonth);  //nextMonth=2023-05-01T16:14:45.898
            return nextMonth;
        });

        LocalDateTime nextMonth = now.with(adjuster);
        System.out.println(nextMonth);  //2023-05-01T16:14:45.898

还有更简单的!!! 使用TemporalAdjusters工具类

4.2.7 ZonedDateTime 时区讲解

     java8中加入了对时区的支持,localDate、LocalTime、LocalTime是不带时区的,带时区的日期时间类分别为:ZonedDate、ZonedTime、ZonedDateTime

   其中,每个时区都对应着ID,ID的格式为"区域/城市",例如:Asia/Shanghai等

    ZoneId:该类中包含了所有的时区信息

//     1.获取所有时区ID
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        for(String zone :availableZoneIds ){
            System.out.println(zone);
        }

  •    ZonedDateTime: 包含时区的时间
//      2.获取标准时间 ZonedDateTime.now(Clock.systemUTC());
//         因为我们是东八区,比标准时间(本初子午线所在时区)快八个小时
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);  //2023-04-10T00:05:36.146
        ZonedDateTime bz = ZonedDateTime.now(Clock.systemUTC());
        System.out.println(bz);             //2023-04-09T16:05:36.146Z

//      3.使用计算机默认的时区创建日期时间
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);  //  2023-04-10T00:05:36.146+08:00[Asia/Shanghai]

//       4. 使用指定的时期创建日期时间
        ZonedDateTime now1 = ZonedDateTime.now(ZoneId.of("America/Marigot"));
        System.out.println(now1);//2023-04-09T12:05:36.147-04:00[America/Marigot]

        Java中使用的历法是ISO 8601日历系统,它是世界民用历法,也就是我们所说的公历。平年有365天,闺年是366天。此外Java 8还提供了4套其他历法,分别是:

  •    ThaiBuddhistDate: 泰国佛教历
  •    MinguoDate: 中华民国历
  •    JapaneseDate:日本历
  •     HiirahDate: 伊斯兰历

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/411414.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Doris(6):数据导入(Load)之Stream Load

Broker load是一个同步的导入方式&#xff0c;用户通过发送HTTP协议将本地文件或者数据流导入到Doris中&#xff0c;Stream Load同步执行导入并返回结果&#xff0c;用户可以通过返回判断导入是否成功。 1 适用场景 Stream load 主要适用于导入本地文件&#xff0c;或通过程序…

小厂实习要不要去?

大家好&#xff0c;我是帅地。 最近暑假实习招聘&#xff0c;不少 训练营 学员都拿到了小厂实习来保底&#xff0c;但是很多小厂基本要求一周内给答复&#xff0c;中大厂就还在流程之中&#xff0c;所以很纠结小厂实习要不要去。 不知道你是否有这样的纠结&#xff0c;今天帅地…

【测试面试汇总2】

目录Linux操作系统1.Linux操作命令2.在Linux中find和grep的区别&#xff1f;3.绝对路径用什么符号表示&#xff1f;4.当前目录、上层目录用什么表示&#xff1f;5.主目录用什么表示&#xff1f;6.怎么查看进程信息&#xff1f;7.保存文件并退出vi 编辑?8.怎么查看当前用户id&a…

【Python从入门到进阶】15、函数的定义和使用

接上篇《14、字典高级应用》 上一篇我们学习了有关字典的高级应用操作&#xff08;字典的增删改查&#xff09;&#xff0c;本篇我们来学习Python中函数的定义和使用&#xff0c;包括函数的参数、返回值、局部变量和全景变量等操作。 一、一个思考 例如这里有一段大东北洗浴中…

2023年PMP报考时间安排攻略!

1.2023年PMP考试时间 PMP一年开考4次&#xff0c;分别为3月、6月、9月、12月&#xff0c;预计2023年PMP第一次考试时间在2023年3月左右&#xff0c;具体以基金会官方通知为准。 1&#xff09;为什么考PMP&#xff1f; 大部分人考 PMP 无非以下几个原因&#xff0c;总的来说&…

运行时内存数据区之程序计数器

内存是非常重要的系统资源&#xff0c;是硬盘和CPU的中间仓库及桥梁&#xff0c;承载着操作系统和应用程序的实时选行。JVM内存布局规定了Java在运行过程中内存申请、分配、管理的策略&#xff0c;保证了JVM的高效稳定运行。 不同的VM对于内存的划分方式和管理机制存在着部分差…

算法时间复杂度计算

目录 1.时间复杂度计算 1.1 时间复杂度例题 1.1.1例题 1.1.2例题 1.1.3例题 1.1.4例题 1.2时间复杂度leetcode例题 1.时间复杂度计算 首先&#xff0c;我们需要了解时间复杂度是什么&#xff1a;算法的时间复杂度是指算法在编写成可执行程序后&#xff0c;运行时需要耗费…

一天吃透操作系统八股文

操作系统的四个特性&#xff1f; 并发&#xff1a;同一段时间内多个程序执行&#xff08;与并行区分&#xff0c;并行指的是同一时刻有多个事件&#xff0c;多处理器系统可以使程序并行执行&#xff09; 共享&#xff1a;系统中的资源可以被内存中多个并发执行的进线程共同使…

MATLAB | 给热图整点花哨操作(三角,树状图,分组图)

前段时间写的特殊热图绘制函数迎来大更新&#xff0c;基础使用教程可以看看这一篇&#xff1a; https://slandarer.blog.csdn.net/article/details/129292679 原本的绘图代码几乎完全不变&#xff0c;主要是增添了很多新的功能&#xff01;&#xff01;&#xff01; 工具函数完…

FastChat开放,媲美ChatGPT的90%能力——从下载到安装、部署

FastChat开放&#xff0c;媲美ChatGPT的90%能力——从下载到安装、部署前言两个前置软件创建FastChat虚拟环境安装PyTorch安装 FastChat下载 LLaMA&#xff0c;并转换生成FastChat对应的模型Vicuna启动FastChat的命令行交互将模型部署为一个服务&#xff0c;提供Web GUI前言 最…

Cesium:自定义MaterialProperty

在项目中应用Cesium.js时,时常遇到需要对Cesium.js的Material材质或者MaterialProperty材质属性进行拓展的应用场景。如果对GLSL(openGL Shading Language ),即:OpenGL着色语言熟悉的话,参考Cesium官方文档,构建一个新的Material必定不是难事。而MaterialProperty材质属…

【C语言进阶:动态内存管理】动态内存函数的介绍

本节重点内容&#xff1a; malloc 和 free 函数calloc 函数realloc 函数&#x1f338;为什么存在动态内存分配 到目前为止&#xff0c;我们已经掌握的内存开辟方式有两种&#xff1a; 创建变量&#xff1a;int val 20; //在栈空间上开辟四个字节 创建数组&#xff1…

Html5钢琴块游戏制作与分享(音游可玩)

当年一款手机节奏音游&#xff0c;相信不少人都玩过或见过。最近也是将其做了出来分享给大家。 游戏的基本玩法&#xff1a;点击下落的黑色方块&#xff0c;弹奏音乐。&#xff08;下落的速度会越来越快&#xff09; 可以进行试玩&#xff0c;手机玩起来效果会更好些。 点击…

【Python】基于serial的UART串口通信(可实现AT指令自动化 以ML307A开发板为例)

【Python】基于serial的UART串口通信&#xff08;可实现AT指令自动化 以ML307A开发板为例&#xff09; Python下的串口serial库 串行口的属性&#xff1a; name:设备名字 portstr:已废弃&#xff0c;用name代替 port&#xff1a;读或者写端口 baudrate&#xff1a;波特率 byt…

Charles 安装及配置,详细步骤(不错,保存一下)

一、安装激活 1.1、下载 https://www.charlesproxy.com/download/ 1.2、激活 打开Charles > Help > Register Charles > 输入 Registered Name &#xff1a; https://zhile.io License Key&#xff1a;48891cf209c6d32bf4 二、代理配置 2.1、代理设置 Proxy > Pr…

Nodejs中的fs模块

一、文件写入操作 writeFile 直接打开文件默认是 w 模式&#xff0c;所以如果文件存在&#xff0c;该方法写入的内容会覆盖旧的文件内容 语法&#xff1a; writeFile(file, data[, options], callback)异步writeFileSync(file, data)同步 参数&#xff1a; file文件名data要…

MYSQL 2:一条更新语句是如何进行的

一. MYSQL的一条更新语句如何进行的&#xff1f; 和查询一样&#xff0c;一开始我们需要通过连接器连接到MYSQL服务器上&#xff0c;然后我们会将我们的语句交给解析器&#xff0c;然后交给执行器。比如我们执行一条这样的语句 update cc1 from user_info where id 2 1.执行…

PTA:C课程设计(5)

山东大学&#xff08;威海&#xff09;2022级大一下C习题集&#xff08;5&#xff09;函数题5-6-1 求一组数中的平均值及最大值5-6-2 判断满足条件的三位数5-6-3 函数实现字符串逆序5-6-4 查找子串5-6-5 计算最长的字符串长度5-6-6 二分查找编程题5-7-1 找最长的字符串5-7-2 藏…

第七天sql优化篇

一、查询SQL尽量不要使用select *&#xff0c;而是select具体字段 因为select * 进行查询时&#xff0c;很可能就不会使用到覆盖索引了&#xff0c;就会造成回表查询 select stu.name from student stu; 二、如果知道查询结果只有一条或者只要最大/最小一条记录&#xff…

CMMI认证唯一查询官网

CMMI是“能力成熟度模型集成”的意思。是一种评估或者认证制度。最新的CMMI V2.0模型有四个视图&#xff0c;DEV开发视图、SVC服务视图、供应商、人力资源&#xff0c;目前开发视图是全球应用最广泛的&#xff0c;主要是由CMMI研究院主任评估师按照CMMI模型检查企业或组织的软件…