2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
The current time is automatically set when inserting data, and the date is automatically modified to the date of modification when updating data.
Use the extended interface MetaObjectHandler of MybatisPlus
Implementing the interface
Annotating entity classes
package com.example.vueelementson.common;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @BelongsProject: blog-springboot
* @BelongsPackage: com.example.vueelementson.common
* @Author: Zww
* @CreateTime: 2024-07-07 16:38
* @Description: TODO
* @Version: 1.0
*/
@Component
public class ExtraDataHandle implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// 第一个值填入你要设置的字段名,第二个值为每次自动填充的值
metaObject.setValue("publishTime", new Date());
metaObject.setValue("updateTime", new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
However, the Date here is given to the front end in timestamp format.
, we add a timestamp conversion js on the front end, import it and call it in the method
// 时间戳:1637244864707
/* 时间戳转换为时间 */
export default {
timestampToTime(value, type = 0) {
var time = new Date(value);// 2023-07-07 17:07:44
var year = time.getFullYear();// 2023年
var month = time.getMonth() + 1; // 0-11 +1表示1-12月
var date = time.getDate();// 1-31号
var hour = time.getHours();// 0-23时
var minute = time.getMinutes();// 0-59分
var second = time.getSeconds();// 0-59秒
month = month < 10 ? "0" + month : month;// 如果小于10的月份,前面补0
date = date < 10 ? "0" + date : date;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
var arr = [
year + "-" + month + "-" + date,
year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second,
year + "年" + month + "月" + date,
year + "年" + month + "月" + date + "日" + " " + hour + ":" + minute + ":" + second,
hour + ":" + minute + ":" + second
]
return arr[type];
}
}
result