【问题标题】:Is there a way to get the local time and time of an oracle database server using java's LocalDateTime class?有没有办法使用java的LocalDateTime类获取oracle数据库服务器的本地时间和时间?
【发布时间】:2020-08-17 22:07:30
【问题描述】:

要获取我机器位置的当前时间,并使用它的值来设置 jpql 查询的参数,这段代码可以正常工作:

LocalDateTime now = LocalDateTime.now();
query.setParameter("myTime", Timestamp.valueOf(now)); //using the current machine time to set parameter for a jpql query

在不同的测试用例中,我想使用 oracle 数据库所在系统的当前时间值,而不是我本地机器的值。有没有办法使用相同的LocalDateTime 类来获得它?如果无法使用此类,解决此问题的最佳方法是什么?

【问题讨论】:

  • 嗯,这取决于您使用的 JPA 提供程序。由于您提到了 JPQL,您可能没有使用条件查询,因此如果您的提供程序是 Hibernate,您可能会幸运地使用内置的 HQL 函数current_timestamp()。但是,数据库的时间应该与您的应用程序的时间相同(服务器应该使用计时服务来保持时间一致),因此这无关紧要。 (不同的时区实际上意味着不同的时间,只是不同的表示)。
  • @Thomas,你能演示一下current_timestamp() 在我的代码中的用法吗?
  • 因为你没有发布太多很难做到的代码。但是,假设您的查询看起来像 ... where xxx = :myTime,您应该能够使用 ... where xxx = current_timestamp() 代替(再次:这是指 Hibernate,我不确定其他 JPA 提供程序)
  • @Thomas,实体类中的查询是这样的:@NamedQuery(name = "findByTime", query = "select u from TestEntity u where u.date < :myTime")

标签: java timezone jpql java-time localdatetime


【解决方案1】:

我想使用系统当前时间的值 oracle 数据库驻留,而不是我的本地计算机。是 有没有办法使用相同的 LocalDateTime 类来获得这个?

ZonedDateTime#withZoneSameInstant

返回具有不同时区的此日期时间的副本,保留瞬间。

假设您的 Oracle DB 所在系统的时区是America/New_York。您可以使用此方法在该时区找到LocalDateTime

演示:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // Zone ID of the system where Oracle DB runs
        ZoneId zoneId = ZoneId.of("America/New_York");

        System.out.println(getLocalDateTimeNowAtZoneId(zoneId));
    }

    static LocalDateTime getLocalDateTimeNowAtZoneId(ZoneId zoneId) {
        return ZonedDateTime.now().withZoneSameInstant(zoneId).toLocalDateTime();
    }
}

输出:

2020-08-17T18:37:04.456820

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2017-08-18
    • 2013-08-30
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多