【发布时间】:2019-10-07 10:23:23
【问题描述】:
我想将 UTC 日期和时间作为时间戳添加到我的 mysql 数据库中。以前我尝试将 SimpleDateFormat 用作:
//UTC based issued date and expiry date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String currentUtc= sdf.format(new Date());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = (Date) simpleDateFormat.parse(currentUtc); //java.util.date
它有效,但我发现不建议使用 SimpleDateFormat。所以现在我使用 Instant date time api 作为:
Instant currentInstant = Instant.now().truncatedTo(ChronoUnit.SECONDS); //gives UTC datetime
这正确地给了我当前的 UTC 时间。 问题是当我将此瞬间添加到我的数据库时,它会通过将我的 UTC 时间偏移添加到我不想要的那个瞬间来转换为本地日期。
//adding UTC time to database but not working
ps.setTimestamp(1, Timestamp.from(currentInstant));
那么如何在不向我的数据库中添加 UTC 时间偏移量的情况下添加 UTC 日期?提前谢谢你。
【问题讨论】:
-
你保存到什么 MySQL 数据类型?我没有经验,但我希望
timestamp在 UTC 日期时间上比datetime工作得更好。 -
我正在保存到我的 mysql 数据库中的 Timestamp 数据类型