关于时间转换的问题?
场景: 如下图, 红框中的数据是后台传过来的时间, 因为是一串字符串, 在 ts 中我就没办法对这个时间做处理 (例如转成数字、获取年月日等)

对应的 ts 代码
un_queryAll() {
this.iconService.queryAll().subscribe((res: { icons?: Icon[] }) => {
this.dataSource.sort = this.sort;
console.log(Date.now());
if (res.icons) {
this.dataSource.data = res.icons;
console.log(res.icons[0].createTime)
}
console.log(res.icons)
});
}问题简述1: 我在model中定义的 createTime 和 updateTime, 都是 number 类型, 并且我在接收 res 时候已经指定接收对象是一个 Icon 类型的数组了, 但为什么我最终 res.icons[0].createTime 结果是一串字符串?
export interface Icon {
id: number;
name: string;
enabled: boolean;
createBy: string;
updateBy: string;
createTime: number;
updateTime: number;
}后台的实体类中, 用的是 Timestamp 类来存储时间
@Column
@CreationTimestamp
private Timestamp createTime;在 mysql 中, 该属性是 DATETIME 类型
`create_time` DATETIME(6) DEFAULT NULL问题简述2: 如何实现当后台先将时间转成数字(时间戳)再传给前台, hibernate有没有什么注解可以支持这个功能的?
回复
1个回答
test
2024-06-29
typescript中的interface仅仅只是类型定义,跟Java中的POJO类是不一样的,因为typescript需要兼容javascript导致其反射能力非常薄弱,并不能自动将json中的string类型映射为number类型(当然可以使用第三方插件实现类似效果,比如class-transformer等)。虽然你的createTime定义为number类型,但是实际返回数据json中的createTime为string类型,最终的结果也只会是string类型。interface的定义应该按照实际数据类型定义,否则只会欺骗编译器的静态检查。如果后端使用的是
Jackson,那么可以使用@JsonFormat注解来快速格式化时间,示例如下:public class DemoObject { @JsonFormat(shape = JsonFormat.Shape.NUMBER) private Date date; }也可以使用Spring自带的
@DateTimeFormat注解,示例如下:public class DemoObject { @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) private Date date; }
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容