时间转换问题 数据库中存储时间毫秒值


因为数据库中的字段create_time是bigint类型,也就是说要在数据库中存储毫秒值,相应的DTO中的createTime字段为Long类型(代码生成器生成),这样带来一些问题。

新增时,直接在后端添加 当前时间 即可:

@Override
    public void save(BaseFishProductSkuDTO dto) {
        SysUserDTO sysUserDTO = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
        dto.setCreateUser(sysUserDTO.getId().toString());

        dto.setDelFlg("1");
        // 新增时获取 当前时间 并设置到dto中,使用系统默认时间即可
        dto.setCreateTime(System.currentTimeMillis());
        dto.setUpdateTime(System.currentTimeMillis());
        super.save(dto);
    }

查询时,在前段页面中肯定是要显示格式化的日期的,因此在DTO中添加String类型的日期字符串,返回给前端用以显示

那么就面临一个问题,如何把Long类型的毫秒值转化为指定格式的日期字符串?
代码如下:

@Override
    public PageData<BaseFishProductTypeDTO> page(Map<String, Object> params) {

        PageData<BaseFishProductTypeDTO> page = super.page(params);
        List<BaseFishProductTypeDTO> baseFishProductTypeDTOList = page.getList();

        for (BaseFishProductTypeDTO baseFishProductTypeDTO : baseFishProductTypeDTOList) {
            // 先将Long类型的毫秒值转换为LocalDateTime类型
            LocalDateTime createTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(baseFishProductTypeDTO.getUpdateTime()), ZoneId.systemDefault());
            LocalDateTime updateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(baseFishProductTypeDTO.getCreateTime()), ZoneId.systemDefault());

            // 再将LocalDateTime类型格式化为指定格式的日期字符串
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
            String jsonCreateTime = dateTimeFormatter.format(createTime);
            String jsonUpdateTime = dateTimeFormatter.format(updateTime);

            baseFishProductTypeDTO.setJsonCreateTime(jsonCreateTime);
            baseFishProductTypeDTO.setJsonUpdateTime(jsonUpdateTime);
        }

        return page;
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM