【发布时间】:2017-05-27 08:10:44
【问题描述】:
我正在获取字符串格式的 UTC 时间,我们需要将其保存到数据库中。
来自 UTC 日期时间字符串 使用以下代码创建的日历对象。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
OffsetDateTime dateTime = OffsetDateTime.parse(rqTime,formatter);
System.out.println(dateTime);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(Date.from(dateTime.toInstant()));
然后将上面创建的日历实例设置为JPA
EventDetails eventDetails = new EventDetails();
eventDetails.setTimeWithZone(cal);
event.insertEventDetails(eventDetails);
实体类信息
@Entity
@Table(name="mytimestamptz")
public class EventDetails implements Serializable{
private static final long serialVersionUID = 1L;
@Column(name ="made_on" , columnDefinition = "TIMESTAMP WITH TIME ZONE")
@Type(type="com.elitecore.isl.bl.xlink.custom.UTCCalendarType")
private Calendar timeWithZone ;
@Id
@SequenceGenerator(name = "generator", sequenceName = "SEQ_EVENTID", allocationSize = 1)
@Column(name ="id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
private Long id;
即使我们已指定时区信息,此代码也会在数据库中插入 UTC 日期字符串“2016-01-01T13:14:15+0000”为“01-JAN-2016 13:14:15 +0530”(请参阅 UTCCalendarType )。
UTCCalendarType 创建用于在数据库中以 UTC 格式存储日期时间
public class UTCCalendarType extends CalendarType {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
/**
* This is the original code from the class, with two changes. First we pull
* it out of the result set with an example Calendar. Second, we set the new
* calendar up in UTC.
*/
@Override
public Object get(ResultSet rs, String name) throws SQLException {
Timestamp ts = rs.getTimestamp(name, new GregorianCalendar(UTC));
if (ts != null) {
Calendar cal = new GregorianCalendar(UTC);
cal.setTime(ts);
return cal;
} else {
return null;
}
}
@Override
public void set(PreparedStatement st, Object value, int index) throws SQLException {
final Calendar cal = (Calendar) value;
cal.setTimeZone(UTC);
System.out.println("IST TIME : "+cal.getTime());
st.setTimestamp(index, new Timestamp(cal.getTime().getTime()),Calendar.getInstance(UTC));
}
}
我没有发现这段代码出了什么问题。 为什么将 ASIA/KOLKATA TIMEZONE 存储在数据库中。 请就此提供宝贵意见。
【问题讨论】:
-
我不知道 java/jpa 所以这可能是一个愚蠢的问题,但是将值插入数据库的代码在哪里?你是如何传递时间戳值的?我的猜测是您的数据库服务器设置在 ASIA/KOLKATA 时区,并且当您传递时间戳值时,您没有指定时区(是的,我知道“Z”表示 ISO 时间戳格式中的 UTC,但 Oracle db 在其时区格式掩码中没有任何附加意义),因此时间戳值被存储为好像它在本地时区而不是 UTC 中一样。
标签: java oracle jpa timestamp-with-timezone