【问题标题】:how to calculate difference between two LocalTime and save in the variable to be saved in the bank?如何计算两个 LocalTime 之间的差异并保存在要保存在银行中的变量中?
【发布时间】:2021-02-19 19:02:58
【问题描述】:

我正在建立一个系统,用户将在其中插入事件(动作)的进入时间和离开时间,当他发布帖子时,我的系统将计算这两个时间之间的差异并保存在可变持续时间。我看不到怎么做,所以我就这样尝试了

@PrePersist public Acao calculoDiferenca() {

    LocalDateTime inicio = LocalDateTime.of(entrada.getYear(), entrada.getMonth(), entrada.getDayOfMonth(),
            entrada.getHour(), entrada.getMinute(), entrada.getSecond());
    LocalDateTime fim = LocalDateTime.of(saida.getYear(), saida.getMonth(), saida.getDayOfMonth(), saida.getHour(),
            saida.getMinute(), saida.getSecond());
    Duration duration = Duration.between(inicio, fim);
    duracao = duration;
    
    System.out.println(duration);
    System.out.println("Days between " + inicio + "e" + fim + ":" + duration.toHours());

    return this;

}

那么如何计算存入可变久期,然后存入银行呢?

我认为 LocalDateTime 会更好,因为我可能会遇到问题,因为会有一天到另一天的事件?例如:开始于 2021-02-02 23:55:32 结束于 2021-02-03 00:02:21

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is java.lang.RuntimeException: Callback methods annotated on the bean class must return void and take no arguments: javax.persistence.PrePersist - public br.com.lucas.entity.Acao br.com.lucas.entity.Acao.calculoDiferenca()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.3.3.jar:5.3.3]

如果您需要查看更多部分,请按照我的代码: https://github.com/Akssasori/ApiRestfull-Merchandising

【问题讨论】:

  • 你没有提到你想用diff做什么。
  • 会将差异放在持续时间内以将其保存在银行中
  • 您可以使用duracao.toHoursPart()duracao.toMinutesPart()duracao.toSecondsPart()分别获取小时、分钟和秒。

标签: java spring-boot api spring-data-jpa localtime


【解决方案1】:

您可以使用localDateOne.toEpochDay() - localDateTwo.toEpochDay(); 获取日期之间的差异(长)。 然后您可以从差异中获取Locadate:

LocalDate.ofEpochDay(localDateOne.toEpochDay() - localDateTwo.toEpochDay());

【讨论】:

  • 但在这种情况下,我只需要小时、分钟和秒的差异
【解决方案2】:

这种方法存在于Duration 类本身中:

Duration duration = Duration.between(inicio, fim);

【讨论】:

  • 是的,但是要在发布后完成此计算,然后不会像您希望的那样保存在银行中,就像您知道的预存一样?
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多