我将日期时间戳存储在数据库中作为UTC值,当需要检索回来时,我需要将其转换为UTC时间并转换为特定的时区值。
即,将2015年5月1日00:09:30:00 UTC时间转换为IST(或其他时区)。
resultSet.getDate("VisitDate")
请帮忙处理这个问题。
我将日期时间戳存储在数据库中作为UTC值,当需要检索回来时,我需要将其转换为UTC时间并转换为特定的时区值。
即,将2015年5月1日00:09:30:00 UTC时间转换为IST(或其他时区)。
resultSet.getDate("VisitDate")
请帮忙处理这个问题。
你可以使用设置为UTC的ZonedDateTime
,然后使用类似以下方式将其转换为LocalDateTime
...
java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC"));
LocalDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
显然,在本示例中我使用了ZoneId.systemDefault()
(将带时区的日期/时间转换为本地日期/时间),但您可以传递任何您想要/需要的时区。
如果您没有使用Java 8,则同样适用于Joda-Time。
java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
LocalDateTime utcDateTime = new LocalDateTime(ts, DateTimeZone.UTC);
DateTime hereDateTime = utcDateTime.toDateTime(DateTimeZone.getDefault());
private final static String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
public static String getCurrentTimeInUTC(){
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
您可以将UTC字符串更改为任何已知的时区字符串以获取该格式。如果这有帮助,请投票。 要更改时区,您可以使用此函数
public static String getLocalTime(String timeZone) throws ParseException{
DateFormat formatter = null;
Date convertedDate = null;
DateFormat outputFormat=new SimpleDateFormat(DATEFORMAT);
formatter = new SimpleDateFormat(DATEFORMAT);
formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
convertedDate = (Date) formatter.parse(getCurrentTimeInUTC());
return outputFormat.format(convertedDate);
}
享受吧 :-)
如您所说,当加载到数据库时,您设置为UTC时区。但是,当从数据库检索时区时,它可能不再是UTC,因为DB不会存储时区信息。有关更多详细信息,请查看此链接Dealing with Timezones in DB。
因此,根据这个链接,它可能会返回本地JVM或DB服务器时区设置的时区。
无论如何,要更改时区,如其他答案中所述,可以使用SimpleDateFormat
。
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
Calendar
是 UTC,但实际情况可能并非如此。例如,在 h2 中,默认的Calendar
是Calendar.getInstance()
,即系统日历。我们需要做的是ZoneId dbZoneId = ZoneId.of("Europe/London"); Calendar dbCalendar = Calendar.getInstance(TimeZone.getTimeZone(dbZoneId)); TimeStamp ts = resultSet.getTimestamp("VisitDate", dbCalendar);
。这将使用存储字段时使用的日历来检索Timestamp
实例。 - Brett Ryan