当我创建一个新Date对象时,它会初始化为当前时间但在本地时区.如何获得GMT中的当前日期和时间?
我的要求是将所有日期和日期时间以UTC时区存储在数据库中.我正在使用Java 8 LocalDate和LocalDateTime我的Hibernate实体.
那是正确的,因为LocalDate与LocalDateTime不具有与之相关联的时区?
如果没有,我应该回到使用好旧(或传统?)Date&Timestamp?
或者我应该使用Java 8 Instant?如果使用Instant,是否有可能只存储日期部分,没有时间?
数据库是MySQL和SQL Server,这是一个Spring Boot应用程序.
这似乎是一个愚蠢的问题,但我无法理解这种令人毛骨悚然的行为。我完全知道 javaDate类没有在其中存储任何 TimeZone 信息的事实。它只存储自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来的毫秒数
问题是,我使用的是驻留在具有 UTC 时区的服务器上的 MySql,并且我也DateTime仅存储在 UTC 中。如果我进行选择查询,那么我会得到这个日期2014-01-17 16:15:49
通过使用http://www.epochconverter.com/我得到了这个:
Epoch timestamp: 1389975349
Timestamp in milliseconds: 1389975349000
Human time (GMT): Fri, 17 Jan 2014 16:15:49 GMT
Human time (your time zone): Friday, January 17, 2014 9:45:49 PM
Run Code Online (Sandbox Code Playgroud)
现在是 Hibernate 的部分。我在以 IST 作为系统时区的机器上运行我的 Java Web 应用程序。我使用 Id 和createdDate作为Date对象的fetched属性做了一个简单的对象提取。我写了一个简单的代码来理解它的输出,这里是代码:
Date dt = c.getCreatedDate();
System.out.println(dt.getTime());
System.out.println(dt);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm …Run Code Online (Sandbox Code Playgroud) 我试过了
user.timezone=UTC 在 config/application.propertiesuser.timezone=GMT在pom.xml中:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<properties>
<spring-boot.run.jvmArguments>-Duser.timezone=UTC</spring-boot.run.jvmArguments>
</properties>
</configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)但它打印出来
System.out.println(TimeZone.getDefault());
Run Code Online (Sandbox Code Playgroud)
sun.util.calendar.ZoneInfo [id =“ America / New_York”,offset = -18000000,dstSavings = 3600000,useDaylight = true,transitions = 235,lastRule = java.util.SimpleTimeZone [id = America / New_York,offset =- 18000000,dstSavings = 3600000,useDaylight = true,startYear = 0,startMode = 3,startMonth = 2,startDay = 8,startDayOfWeek = 1,startTime = 7200000,startTimeMode = 0,endMode = …