Java:如何将时间输入为字符串并计算差异

时间:2016-02-07 05:20:19

标签: java time

我想制作一个用户输入开始时间和结束时间的java程序。从那里我希望程序计算时间之间的差异? 这应该是输出

Enter first time: 12:56 pm
Enter second time: 1:03 pm
time difference is 7 minutes

我只知道如何计算和找到分钟的公式。

3 个答案:

答案 0 :(得分:3)

抱歉,我不太清楚你需要什么。如果要将用户输入的时间转换为时间戳,然后计算差异,这将有所帮助:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Time {
public static void main(String args[]) throws ParseException{
Scanner input = new Scanner(System.in);
 System.out.print("Enter first time (hh:mm aa): ");
 String time = input.nextLine();
 System.out.println();
 System.out.print("Enter second time (hh:mm aa): ");
 String time2 = input.nextLine();
 System.out.println();
 DateFormat sdf = new SimpleDateFormat("hh:mm aa");
 Date d1 = sdf.parse(time);
 Date d2 = sdf.parse(time2);

 System.out.println("Time: " + sdf.format(d1));
 System.out.println("Time: " + sdf.format(d2));
    if(d1.after(d2)){
     long diffMs = d1.getTime() - d2.getTime();
     long diffSec = diffMs / 1000;
     long min = diffSec / 60;
     long sec = diffSec % 60;
     System.out.println("The difference is "+min+" minutes and "+sec+" seconds.");
    }

    if(d1.before(d2)){
     long diffMs = d2.getTime() - d1.getTime();
     long diffSec = diffMs / 1000;
     long min = diffSec / 60;
     long sec = diffSec % 60;
     System.out.println("The difference is "+min+" minutes and "+sec+" seconds.");
    }

    if(d1.equals(d2)){
     System.out.println("The difference is 0 minutes and 0 seconds.");
    }

 }
}

唯一的限制是你必须限制你的用户以给定的格式输入时间,允许用户输入任何格式的时间都会让你无法处理。

我希望它有所帮助:)

答案 1 :(得分:0)

String startTime = "08/16/2011 12:56:00";
String endTime = "08/16/2011 13:56:00";

// Customize your own date format
SimpleDateFormat format = new SimpleDateFormat("MM/DD/YYYY hh:mm:ss");
Calendar c = Calendar.getInstance();

c.setTime(format.parse(startTime));
long startMillis = c.getTimeInMillis();

c.setTime(format.parse(endTime));
long endMillis = c.getTimeInMillis();

System.out.println("time difference is " + ((endMillis - startMillis)/1000) + " seconds");

答案 2 :(得分:0)

使用正则表达式以HH:MM:SS格式接受来自用户的时间

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetTime {

public static void main(String[] args) {

    String ip="";
    String pattern="^([01]?\\d|2[0-3]):([0-5]?\\d):([0-5]?\\d)$";

    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the time");
    ip=sc.nextLine();
    Pattern r = Pattern.compile(pattern);
     Matcher m = r.matcher(ip);
     if(m.find())
     {
         System.out.println("Time"+m.group(0));
         System.out.println("hh "+m.group(1));
         System.out.println("mm "+m.group(2));
         System.out.println("ss "+m.group(3));
     }
     else
     {
         System.out.println("NO MATCH! format mismatch");
     }
 }
}