因為數據庫中的字段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;
}