如何在Java中的预期时区中检索oracle Timestamp列?

时间:2016-06-17 06:12:08

标签: java oracle datetime

我在oracle表中有一个timestamp列。存储时间我在此列中以UTC格式存储。为了检索这个时间戳,我使用的是Spring的JdbcTemplate,同时返回TimeStamp类型的对象。

我希望将日期时间字符串输入" dd-MM-YYYY HH:mm:ss"当前时区的格式。为了实现这一点,我正在尝试以下代码:

new LocalDateTime(<retrieved TimeStamp>, <current user DateTimeZone>).toString("yyyy-MM-dd HH:mm:ss")

来自Joda图书馆的LocalDateTime和DateTimeZone。

然而,这并不是按预期工作的。而不是当前用户在代码上面的时区只给出了UTC日期时间字符串。

我错过了什么?

2 个答案:

答案 0 :(得分:4)

我认为您的应用程序使用的java.util.Date没有时区信息,toString用法在创建字符串时应用JVM的当前默认时区。

您可以按(Using Joda Library

调整时区
ZonedDateTime Tokyo = ZonedDateTime.ofInstant (instant,zoneIdTokyo) ;

或实施区域

DateTimeZone zone = DateTimeZone.forID("Asia/Tokyo");

您正在使用 LocalDateTime,它是表示本地日期和时间(无时区)的不可变类

编辑 - 您可以试试这个 (我没有测试过它)

DateTime udate = new DateTime("2016-05-01T20:10:04", DateTimeZone.UTC);
System.out.println(udate);
DateTime zone = udate.plusMillis(10000)
.withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(zone);

答案 1 :(得分:2)

从数据库中获取时间戳时添加utc日历,因此jdbc驱动程序可以使用此日历时区而不是默认系统时区。

//Assign utc calendar
Calendar utc= Calendar.getInstance();
utc.setTimeZone(TimeZone.getTimeZone("UTC"));
Timestamp timestamp = rs.getTimestamp("timestampcolumn", utc);
//Convert to client date time
DateTime dateTime = new DateTime(timestamp.getTime(), DateTimeZone.forID("Asia/Kolkata"));
//Format
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
//Change to client wall clock time
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime)

示例

String utcTime = "2016-06-17 14:22:02Z";
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");
DateTime dateTime = parser.parseDateTime(utcTime).withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
System.out.println(dateTime);
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime);
System.out.println(formattedlocalDateTime);