如何用JAVA计算用户输入的时间



嘿,伙计们,我需要帮助来计算两个特定时间之间的时差(由用户输入(。但输出必须以小时、分钟和秒为单位,作为它们自己的变量。

示例:

开始时间:

小时:15分钟:50第二个:00

完成时间:

小时:17分钟:14第二:23

结果:1小时24分23秒

编辑:这就是我到目前为止所得到的,这是我的问题的计算

public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);
    System.out.println("Starttime:");
    System.out.println("---------");
    System.out.print("Hour: ");
    int HourS = in.nextInt();
    System.out.print("Minute: ");
    int minuteS = in.nextInt();
    System.out.print("Second: ");
    int secondS = in.nextInt();

    System.out.println("t");
    System.out.println("Finishtime:");
    System.out.println("------------");
    System.out.print("Hour: ");
    int hourF = in.nextInt();
    System.out.print("Minute: ");
    int minuteF = in.nextInt();
    System.out.print("Second: ");
    int secondM = in.nextInt();

使用JodaTime-它做得很好。

  • http://joda-time.sourceforge.net/

这个简单的例子计算两个时间戳之间的差异,并将其打印为可读的:

    String a = "00:01:09:340";
    String b = "00:02:03:430";
    DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss:SSS");
    DateTime oldTime = DateTime.parse(a, format);
    DateTime newTime = DateTime.parse(b, format);
    Interval interval = new Interval(oldTime, newTime);
    System.out.println(new StringBuffer("hours: ").append(interval.toDuration().getStandardHours())
            .append(" minutes: ").append(interval.toDuration().getStandardMinutes()).append(" seconds: ")
            .append(interval.toDuration().getStandardSeconds()).append(" milliseconds: ")
            .append(interval.toPeriod().getMillis()).toString());

该示例将为您提供以下输出:

hours: 0 minutes: 0 seconds: 54 milliseconds: 90

这是以毫秒为单位的差异:

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date = format.parse(time);
Date dateB = format.parse(timeB);
long difference = dateB.getTime() - date.getTime();

您可以将其转换为所需的格式。

public static void main (String [] args) throws Exception
{
    SimpleDateFormat format = new SimpleDateFormat ("'Hour: 'HH' Minute: 'mm' Second: 'ss");
    BufferedReader reader = 
        new BufferedReader (
            new InputStreamReader (System.in));
    System.out.print ("Starting time: ");
    long startingTime = format.parse (reader.readLine ()).getTime ();
    System.out.print ("Finish time: ");
    long finishTime = format.parse (reader.readLine ()).getTime ();
    long delta = finishTime - startingTime;
    long seconds = delta / 1000 % 60;
    long minutes = delta / 60000 % 60;
    long hours = delta / 3600000;
    System.out.println (
        "Result: " + hours + " hour(s) " + minutes + 
        " minute(s) " + seconds + " second(s)");
}

对我来说,输出是:

Starting time: Hour: 15 Minute: 50 Second: 00
Finish time: Hour: 17 Minute: 14 Second: 23
Result: 1 hour(s) 24 minute(s) 23 second(s)

您可能需要考虑使用JODA时间,它支持更复杂的日期计算方法。

相关内容

  • 没有找到相关文章

最新更新