代码应该从数据库中获取日期和时间,将其标记为 UTC(或者也许它应该已经知道它是 UTC?),将其转换为本地时区,然后将日期和时间作为时间戳返回.
目前代码仅打印出数据库中的日期/时间并将本地时间保存到数据库中。
我对代码的解释是否错误?我是否缺少转换时间的步骤?
感谢您的任何额外帮助
package Utils;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class DateTimeConverter {
public static Timestamp toLocalDateTime(Timestamp utc){
//identify as UTC
ZonedDateTime utcZonedDateTime = ZonedDateTime.ofInstant(utc.toInstant(), ZoneId.of("UTC"));
Instant timestamp = utcZonedDateTime.toInstant();
//set the timestamp to the systems default zone
ZonedDateTime utcToLocal = timestamp.atZone(ZoneId.systemDefault());
System.out.println(Timestamp.from(utcToLocal.toInstant()));
return Timestamp.from(utcToLocal.toInstant());
}
public static Timestamp toUTC(Timestamp ldt){
//identify as systems default zoneid
ZonedDateTime localZDT = ZonedDateTime.ofInstant(ldt.toInstant(), ZoneId.systemDefault());
Instant timestamp = localZDT.toInstant();
//set the timestamp to UTC zoneid
ZonedDateTime localToUTC = timestamp.atZone(ZoneId.of("UTC"));
System.out.println(Timestamp.from(localToUTC.toInstant()));
return Timestamp.from(localToUTC.toInstant());
}
}
最佳答案
public static Timestamp toLocalDateTime(Timestamp utc){
LocalDateTime ldt = utc.toLocalDateTime();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("UTC"));
ZonedDateTime newZdt = zdt.withZoneSameInstant(ZoneId.systemDefault());
LocalDateTime newLdt = newZdt.toLocalDateTime();
return Timestamp.valueOf(newLdt);
}
public static Timestamp toUTC(Timestamp ts){
LocalDateTime ldt = ts.toLocalDateTime();
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime newZdt = zdt.withZoneSameInstant(ZoneId.of("UTC"));
LocalDateTime newLdt = newZdt.toLocalDateTime();
return Timestamp.valueOf(newLdt);
}
关于java - 如何从 SQL 日期时间 UTC 转换为 LocalDateTime 并再次转换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60418118/