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

时间:2015-07-04 09:01:50

标签: java time format command-line-arguments

我正在尝试创建一个简单的程序,允许用户使用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());
    }

}

1 个答案:

答案 0 :(得分:0)

&#34;那么,在传递参数之前,你必须将参数解析为LocalTime对象。&#34; -RealSkeptic

这让我得到了我需要的感谢。

// NULL
echo Database::Get('host');