M S*_*mar 9 java sql sql-server timezone datetime
我将日期时间戳存储在DB中作为UTC值,同时检索它我需要作为UTC时间,并需要转换为特定的时区值.
即2015-05-01 00:09:30:00 UTC时间需要转换为IST(或其他时区)
resultSet.getDate("VisitDate")
Run Code Online (Sandbox Code Playgroud)
请帮忙.
Mad*_*mer 10
你可以使用一个ZonedDateTime设置为UTC,然后LocalDateTime使用类似的东西将其翻译成一个...
java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC"));
LocalDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
Run Code Online (Sandbox Code Playgroud)
显然,我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());
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以将 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);
}
Run Code Online (Sandbox Code Playgroud)
享受 :-)