You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC项目中数据库存储时间与页面展示时间不一致问题求助

Spring MVC项目中数据库存储时间与页面展示时间不一致问题求助

大家好,我最近碰到一个头疼的时间显示问题,想请各位帮忙分析解决下。

具体情况是:我用SQL数据库存储的日期时间是完全正确的,但在网页上展示时却出现了偏差,差了好几个小时。举个实际例子:

数据库存储值:2023-05-20 18:12:48(这是我想要的正确时间)
网页展示值:2023-05-21 01:12:48.0(明显不对的时间)

我的业务逻辑是用户点击按钮时,将当前时间存入数据库,数据库里最终存储的时间是符合预期的,但页面渲染出来就不对了。

下面是我的相关代码片段,方便大家排查:

实体类代码

@Entity
@Table(name = "attendance_check_in")
public class AttendanceCheckIn {

    @Column(name = "check_in")
    @Temporal(TemporalType.TIMESTAMP)
    private Date checkIn;

    // getter & setter 方法
}

处理保存请求的Controller代码

@RequestMapping(value = "/attendance-input", method = RequestMethod.POST)
public String inputAttendance(Model model, AttendanceCheckIn attendanceIn, Authentication auth) throws ParseException {
    model.addAttribute("attendanceIn", new AttendanceCheckIn());

    LocalDateTime ldt = LocalDateTime.now();
    Date in = Date.from(ldt.toInstant(ZoneOffset.UTC));
    attendanceIn.setCheckIn(in);

    attendanceInServ.save(attendanceIn);
    return "redirect:/attendance";
}

处理页面展示请求的Controller代码

@RequestMapping(value = "/attendance", method = RequestMethod.GET)
public String attendancePage(Model model) {
    model.addAttribute("attendanceIn", new AttendanceCheckIn());
    // 加载所有签到记录
    model.addAttribute("getAllAttendanceIn", attInServices.getAll());
    return "Attendance";
}

前端Thymeleaf表格代码

<table id="attIn-table"
       class="table table-bordered"
       width="100%"
       cellspacing="0">
    <thead>
        <tr>
            <td>Date & Time</td>
        </tr>
    </thead>
    <tbody>
        <tr th:each="as : ${getAllAttendanceIn}">
            <td th:text="${as.checkIn}"></td>
        </tr>
    </tbody>
</table>

我反复确认了数据库里的存储值是正确的,但就是搞不懂为什么页面展示会出错,有没有大佬能帮我分析下原因,给个可行的解决办法呀?万分感谢!

备注:内容来源于stack exchange,提问作者Danu Pratama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 12:54:34