【问题标题】:Duration between two dates Java [duplicate]两个日期之间的持续时间Java [重复]
【发布时间】:2020-07-15 20:40:25
【问题描述】:

我有 DateTime 字符串 2020-04-03 01:29:27 和 2020-04-03 01:29:37 我想以小时为单位获得持续时间。我尝试了很多东西,但找不到任何帮助

【问题讨论】:

    标签: java datetime between duration


    【解决方案1】:

    我尝试了很多东西,但找不到任何帮助

    做这些“很多事情”包括consulting the javadoc,你会发现:

    // assuming both dates are in d1 and d2
    
    Duration duration = Duration.between(d1, d2);
    
    long hours = duration.toHours(); 
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      java.time

      import java.time.Duration;
      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      
      public class Main {
          public static void main(String[] args) {
              DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
              LocalDateTime dt1 = LocalDateTime.parse("2020-04-03 01:29:27", formatter);
              LocalDateTime dt2 = LocalDateTime.parse("2020-04-03 01:29:37", formatter);
              System.out.printf("%.4f Hour(s)", Duration.between(dt1, dt2).toSeconds() / 3600.0);
          }
      }
      

      输出:

      0.0028 Hour(s)
      

      Trail: Date Time 了解有关 java.time API 的更多信息。

      【讨论】:

      • 还有其他人抱怨它,嗯?
      猜你喜欢
      • 1970-01-01
      • 2018-11-23
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2012-09-28
      相关资源
      最近更新 更多