我的任务是将存储在我的 DB(Sql Server) 表列之一上的时间转换为指定时区。该列始终包含采用 UTC 时区的时间。
我面临的问题是,当 hibernate 读取列并将其设置为我的实体类时,它会在应用程序服务器的时区中设置时间。
例如: 如果 DB 有值 - 2012 年 7 月 7 日 10:30(实际上是 UTC),hibernate 将映射日期字段设置为 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();
使用上面的代码.. 我可以让数据库存储 date 回到 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 的形式输出,因为我需要在这个日期再做一次转换
请帮我解决这个问题
最佳答案
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,再问信息日历:
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));
旁注:不要使用已弃用的方法。他们有充分的理由被弃用。
关于java - 带时区的数据库日期时间到 java.util.Date 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11726883/