【问题标题】:Java - Adding a time variable to the current timeJava - 将时间变量添加到当前时间
【发布时间】:2021-11-07 18:04:39
【问题描述】:

我正在尝试将给定的“持续时间”添加到当前时间。例如,

String runtime = "1h58m"

我正在尝试将其添加到当前时间,以便输出看起来像

The runtime of <movie name> is <runtime>. 
<Name> will end at <calculatedDate> 

其中计算的日期是系统当前时间,加上给定的运行时间。

这是我目前拥有的,但不知道如何将运行时添加到当前系统时间。

public void playMovie(Movie movie){
        SimpleDateFormat df = new SimpleDateFormat("MM/dd/Y hh:mmaa");
        Date date = new Date();
        System.out.println("The runtime of "+name+" is "+runtime);
        System.out.println(""+name+" will end at "+df.format(date));

【问题讨论】:

  • 不要使用Date,而是使用java.time,这样就很简单了。
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APIZonedDateTimeDateTimeFormatter

标签: java datetime java-time duration


【解决方案1】:

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

使用现代日期时间 API java.time 的解决方案:我建议您使用 java.time.Duration,它是在 Java-8 中作为 JSR-310 implementation 的一部分引入的为ISO_8601#Duration建模。

演示:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String runtime = "1h58m";
        runtime = "PT" + runtime;
        Duration duration = Duration.parse(runtime);
        System.out.println(duration);

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endTime = now.plus(duration);
        System.out.println(endTime);

        // Custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm a", Locale.ENGLISH);
        System.out.println(endTime.format(dtf));
    }
}

输出:

PT1H58M
2021-09-11T23:03:58.749831
09/11/2021 11:03 PM

ONLINE DEMO

Trail: Date Time 了解有关现代日期时间 API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

【讨论】:

  • 这是明智的答案。
【解决方案2】:

只需像这样使用 LocalDateTime API(从 java 8 开始):

System.out.println("will end at " + LocalDateTime.now().plusHours(1).plusMinutes(30).plusSeconds(45));

【讨论】:

    【解决方案3】:

    您可以使用如下所示的 LocalTime 类。

    public void playMovie(Movie movie){
    
            // Finding Hours, Minutes, and Seconds from the String runtime
            int n = runtime.length();
            int hours = 0;
            int minutes = 0;
            int seconds = 0;
            int i=0;
            for(int j=1; j<n; j++){
                if(runtime.charAt(j)=='h'){
                    hours = Integer.parseInt(runtime.substring(i,j));
                    i=j+1;
                }
                if(runtime.charAt(j)=='m'){
                    minutes = Integer.parseInt(runtime.substring(i,j));
                    i=j+1;
                }
                if(runtime.charAt(j)=='s'){
                    seconds = Integer.parseInt(runtime.substring(i,j));
                    i=j+1;
                }
            }
    
            //SimpleDateFormat df = new SimpleDateFormat("MM/dd/Y hh:mmaa");
            //Date date = new Date();
            System.out.println("The runtime of "+name+" is "+runtime);
            //System.out.println(""+name+" will end at "+df.format(date));
            
            // Current System Time using the LocalTime class
            LocalTime currentSystemTime = LocalTime.now();  
    
            // Adding the duration of the movie to the current system time
            LocalTime movieEndTime = currentSystemTime
                    .plusHours(hours)
                    .plusMinutes(minutes)
                    .plusSeconds(seconds);
    
            System.out.println(""+name+" will end at "+ movieEndTime);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2019-06-28
      • 2012-12-26
      相关资源
      最近更新 更多