1

我的任务是将存储在我的 DB(Sql Server)表的列中的时间转换为指定的时区。该列始终包含 UTC 时区的时间。

我面临的问题是,当休眠读取列并将其设置为我的实体类时,它会在应用程序服务器的时区设置时间。

例如:如果 DB 具有值 - 2012 年 7 月 7 日 10:30(实际上是 UTC),则休眠将映射日期字段设置为 2012 年 7 月 7 日 10:30 PST(假设 JVM 在 PST 运行)。

现在,如果此日期转换为任何其他时区.. 说 GMT+5:30,我会得到意想不到的结果

要解决上述问题...我编写了以下代码

 //Reading the DB time (which does not have timezone info)
 Date dbDate = entityObj.getDBUtcDate();

 //Setting GMT timezone to the date, without modifying the date
 Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
 c.set(dbDate.getYear(), dbDate.getMonth(), dbDate.getDate()..., dbDate.getMinutes());

 Date utcDate = c.getTime();

使用上面的代码..我可以将数据库存储在UTC区中,但是当我使用以下逻辑转换到其他时区(比如 GMT+5:30)时

Calendar outCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
outCal.setTimeInMillis(utcDate.getTime());

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, outCal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, outCal.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, outCal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, outCal.get(Calendar.HOUR_OF_DAY));                                              
cal.set(Calendar.MINUTE, outCal.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, outCal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, outCal.get(Calendar.MILLISECOND));

//Converted date
Date pstTime = cal.getTime();
//Converted time mill seconds
long timeMilSec = pstTime.getTime();

转换日期的时间毫秒开始为负数(-54672...),这似乎表示无效时间。

我的问题是如何从数据库恢复时区信息(无需在数据库中有任何额外的列来专门存储时区信息)?

或者

如何将数据库时间转换为具有指定时区(UTC)的时间?

PS:我希望以 java.util.Date/Calendar 的形式输出,因为我需要在这个日期再做一次转换

请帮我解决这个问题

4

1 回答 1

5

Java 中的日期没有时区。它们只是一个普遍的瞬间。如果要在给定时区显示日期,则只需使用使用该时区初始化的 DateFormat:

DateFormat df = DateFormat.getInstance();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("The date in the database, in the UTC time zone, is " 
                   + df.format(date));

你不需要转换任何东西。日期格式根据它格式化的通用瞬间以及您告诉它使用的时区打印适当的值。

同样,如果您想知道日期是星期一还是星期二,或者是 1 点钟还是 2 点钟,您需要先选择一个时区,将其转换为日历,然后向日历询问信息:

Calendar cal = Calendar.getInstance(someTimeZone);
cal.setTime(date);
System.out.println("The day for the date stored in the database, for the time zone "
                   + someTimeZone
                   + " is " + cal.get(Calendar.DATE));

旁注:不要使用不推荐使用的方法。有充分的理由不推荐使用它们。

于 2012-07-30T18:06:52.637 回答