Java 命令行参数使用 hh:mm:ss 格式

Java command line arguments using hh:mm:ss format

我正在尝试制作一个简单的程序,允许用户使用 hh:mm:ss 格式的命令行参数输入 startTime 和 stopTime 并打印时钟运行的持续时间。我查看了时间部分的 API,但找不到该格式。我读到您可以通过构造函数传递参数,但这没有用。这是代码:

import java.time.LocalTime;
import java.time.Duration;




public class Clock {
    private LocalTime startTime;
    private LocalTime stopTime;
    private Duration duration;
    private int hours, minutes, seconds;


    // no argument constructor that initializes the startTime to the current time
    public Clock() {
        startTime = LocalTime.now();
    }
    public Clock(LocalTime start, LocalTime stop) {
        startTime = start;
        stopTime = stop;
    }


    //public Clock(start, stop) {

    //}

    // resets the startTime to the given time
    public void start(int h, int m, int s) {
        hours = ((h >= 0 && h < 24) ? h : 0);
        minutes = ((m >= 0 && m < 60) ? m : 0);
        seconds = ((s >= 0 && s < 60) ? s : 0);
        startTime = LocalTime.of(hours, minutes, seconds);
    }

    //a stop() method that sets the endTime to the given time
    public void stop(int h, int m, int s) {
        hours = ((h >= 0 && h < 24) ? h : 0);
        minutes = ((m >= 0 && m < 60) ? m : 0);
        seconds = ((s >= 0 && s < 60) ? s : 0);
        stopTime = LocalTime.of(hours, minutes, seconds);
    }

    //a getElapsedTime() method that returns the elapsed time in seconds
    public Duration getElapsedTime() {
        System.out.println("Difference is " + Duration.between(stopTime, startTime).
            toNanos()/1_000_000_000.0 + " Seconds.");
        duration = Duration.between(stopTime, startTime);
        return duration;
    }

}

这里是 main 方法:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;


public class TestClock {

    public static void main(String[] args) {

       LocalTime argOne;
       LocalTime argTwo;
       argOne = LocalTime.parse(args[0]);
       argTwo = LocalTime.parse(args[1]);
       Clock clockOne = new Clock(argOne, argTwo);
       System.out.println(clockOne.getElapsedTime());
    }

}

"Well, then, you have to parse the arguments into LocalTime objects before you pass them." -RealSkeptic

这让我得到了我需要的东西谢谢。

public class TestClock {

    public static void main(String[] args) {

       LocalTime argOne;
       LocalTime argTwo;
       argOne = LocalTime.parse(args[0]);
       argTwo = LocalTime.parse(args[1]);
       Clock clockOne = new Clock(argOne, argTwo);
       clockOne.getElapsedTime();
    }

}