我以字符串格式获得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 DAte String" 2016-01-01T13:14:15 + 0000" as" 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存储在数据库中。 请提供宝贵的意见。
答案 0 :(得分:0)
可能只是数据表示的问题:日期存储正确,但DBMS(或查询浏览器)以本地格式显示。
您可以使用特定功能(例如,sys_extract_utc(timestamp)
表示ORACLE)或通过查询与其他有效存储日期进行比较来测试是否属于这种情况。
希望它有所帮助。