1、获取当前时间
通过Util包中的Date获取:
import java.util.Date;
Date nowTime = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前日期:"+dateFormat.format(nowTime));//当前日期:2023-02-16 09:34:16
2、显示时间戳,Unix格式 单位毫秒
import org.apache.commons.lang3.time.DateFormatUtils;
Long date=1675239751924L;
String result = DateFormatUtils.format(date/1000 * 1000L, "yyyy-MM-dd HH:mm:ss");
System.out.println("时间:"+result);//时间:2023-02-01 16:22:31
注:时间戳在线转换工具,更详细见:Java与Unix时间戳互转
3、mysql类型为:datetime
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
a.setDate(new Date());
4.springboot中展示的时间比实际时间少8个小时,解决方法
方法一:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
方法二:在配置文件中
spring:
# jackson时间格式化
jackson:
serialization:
FAIL_ON_EMPTY_BEANS: false
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss