【发布时间】:2020-02-19 19:51:43
【问题描述】:
所以最近我一直在我的项目中使用 Calendar 和 Date 数据类型,并且在向我的数据库(使用 Spring 和 Hibernate/MySql5Dialect)插入(和检索)正确的小时数时遇到问题。
当我尝试在我的 spring 应用程序中使用一个存储过程,它会从数据库中选择一些日期(DATETIME 数据类型)时,Java 中返回的对象总是比我的数据库中的实际日期早一小时(例如,2019-03 -30 09:00:00 在我的数据库中,我得到 2019-03-30 08:00:00 从我的服务返回)。现在,当我在 mysql workbench 中调用相同的程序时,它可以完美运行。
现在我注意到,当我尝试从我的 Spring 应用程序中插入带有日期的记录时,例如 2019-03-30 09:00:00,我在我的数据库中得到 2019-03-30 08:00:00 ,这是我插入日期的方式:
private PatientAppointmentDTOR createPatientAppointmentDTOR() {
PatientAppointmentDTOR dtor = factory.manufacturePojo(PatientAppointmentDTOR.class);
dtor.setCpId(5L); // foreign keys...
dtor.setBranchId(2L);
dtor.setPtId(32L);
dtor.setEmployeeId(55L);
dtor.setInDepartmentId(7L);
dtor.setPatientAppointmentStatusId(20L);
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 2019);
cal1.set(Calendar.MONTH, 2);
cal1.set(Calendar.DAY_OF_MONTH,30);
cal1.set(Calendar.HOUR_OF_DAY, 12);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
Date start = cal1.getTime();
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 2019);
cal2.set(Calendar.MONTH, 2);
cal2.set(Calendar.DAY_OF_MONTH,30);
cal2.set(Calendar.HOUR_OF_DAY, 12);
cal2.set(Calendar.MINUTE, 30);
cal2.set(Calendar.SECOND, 0);
cal2.set(Calendar.MILLISECOND, 0);
Date end = cal2.getTime();
dtor.setStartTime(start);
dtor.setEndTime(end);
Company company = companyService.getEntityById(5L);
GroupDTOS gdtos = groupService.getDTOById(2L);
when(auth.userDetails())
.thenReturn(EntityFactory
.createUserDetails(DBStaticFields.Role.CLINIC_ADMIN, company, gdtos, factory));
return dtor;
}
然后我只是使用这个 JUnit 测试将它插入到我的数据库中:
@Test
@DisplayName("test insertion")
void testInsert() {
PatientAppointmentDTOR dtor = this.createPatientAppointmentDTOR();
PatientAppointmentDTOS dtos = patientAppointmentService.insert(dtor);
assertThat(dtos).isNotNull();
assertThat(dtos.getId()).isNotNull();
}
是的,当我从我的应用程序中插入这些值时,我的数据库中的 startDate 是 2019-03-30 11:00:00,endDate 是 2019-03-30 11:30:00。有人知道吗?
【问题讨论】:
-
检查时区:您的应用程序 + 数据库服务器
标签: mysql spring hibernate datetime calendar