Java计算签入和签出之间的时间差

时间:2019-01-16 10:12:30

标签: java time

我想使用Java 日期格式

来计算时差小时和分钟,

用户应输入类似 锁定时间:23:00 超时:01:00

预期输出应为 2小时00分钟

但是我怎么计算它们呢?

Scanner input = new Scanner(System.in);

    //Read data
    System.out.print("Clock In: ");
    String sTimeIn = input.nextLine();

    System.out.print("Clock Out: ");
    String sTimeOut = input.nextLine();

    // Process data
    String sHourIn = sTimeIn.substring(0, 2);
    String sMinuteIn = sTimeIn.substring(3, 5);
    String sHourOut = sTimeOut.substring(0, 2);
    String sMinuteOut = sTimeOut.substring(3, 5);

    int iHourIn = Integer.parseInt(sHourIn);
    int iMinuteIn = Integer.parseInt(sMinuteIn);
    int iHourOut = Integer.parseInt(sHourOut);
    int iMinuteOut = Integer.parseInt(sMinuteOut);

    int sumHour =
    int sumMinute = 

    //Display Output
    System.out.print(sumHour +"Hour "+ sumMinute + " Minute");

}

}

在我查看了您提供的所有解决方案之后。这是我编辑的内容。但我仍然发现一个问题是 如果在23:00时钟中锁定:01:00 ,并且输出为22Hour(s) 0 Minute(s)。输出应为02 Hour(s) 0 Minute(s)

System.out.println("*Your time format must be 00:00");
        System.out.print("Clock In: ");
        String getTimeIn = input.nextLine();

        System.out.print("Clock Out: ");
        String getTimeOut = input.nextLine();

        // Process data
        String sHourIn = getTimeIn.substring(0, 2);
        String sMinuteIn = getTimeIn.substring(3, 5);
        String sHourOut = getTimeOut.substring(0, 2);
        String sMinuteOut = getTimeOut.substring(3, 5);

        int sumHour = Integer.parseInt(sHourIn) - Integer.parseInt(sHourOut);
        int sumMinute = Integer.parseInt(sMinuteIn) - Integer.parseInt(sMinuteOut);

        if(sumHour < 0) {
            sumHour =-sumHour;
        }

        if(sumMinute < 0) {
            sumMinute =- sumMinute;
        }

        //Display Output
         System.out.print(sumHour +"Hour(s) "+ sumMinute + " Minute(s)");

5 个答案:

答案 0 :(得分:2)

正如@Stultuske所说,时间库应该是一个更安全的选择,我在下面提供了一个示例

class GoogleSpec extends GebReportingSpec {

    def "checking for word"() {
        given: " Search for word 'ebay' in google"

        def searchPhrase = "ebay"
        def googlePage = to GoogleHomePage

        when: "I search for ebay"

        def resultsPage = googlePage.searchFor(searchPhrase)

        then: "Correct results are shown"

        resultsPage.countResultsContaining(searchPhrase) == 10
    }
}

更新

该解决方案缺少 @Joakim Danielson 指出的午夜穿越,所以我修改了上述解决方案以检查import java.time.LocalTime; public class HelloWorld { public static void main(String[] args) { LocalTime in = LocalTime.parse("18:20"); LocalTime out = LocalTime.parse("20:30"); int hoursDiff = (out.getHour() - in.getHour()), minsDiff = (int)Math.abs(out.getMinute() - in.getMinute()), secsDiff = (int)Math.abs(out.getSecond() - in.getSecond()); System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff); } } in > out

out < in

答案 1 :(得分:2)

如果要使用Java 8的LocalTimeChronoUnit类:

String sTimeIn = "23:15";
String sTimeOut = "1:30";
LocalTime timeIn = LocalTime.parse(sTimeIn, DateTimeFormatter.ofPattern("H:m"));
LocalTime timeOut = LocalTime.parse(sTimeOut, DateTimeFormatter.ofPattern("H:m"));
long dif = ChronoUnit.MINUTES.between(timeIn, timeOut);
if (dif < 0)
    dif += 24 * 60;
long sumHour = dif / 60;
long sumMinute = dif % 60;

System.out.println(sumHour + ":"+ sumMinute);

或格式化为HH:mm

System.out.println(String.format("%02d", sumHour) + ":"+ String.format("%02d", sumMinute));

将打印:

02:15

答案 2 :(得分:1)

这是我建议的解决方案,包括对输入的一些简单(不是完美的)验证,我将解决方案放在了一个方法中,这样就不会要求用户输入

public static void calcTime(String sTimeIn, String sTimeOut) {
    final String timePattern = "[0-2][0-9]:[0-5][0-9]";

    if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
        throw new IllegalArgumentException();
    }

    String[] timeIn = sTimeIn.split(":");
    String[] timeOut = sTimeOut.split(":");

    int inMinutes = 60 * Integer.valueOf(timeIn[0]) + Integer.valueOf(timeIn[1]);
    int outMinutes = 60 * Integer.valueOf(timeOut[0]) + Integer.valueOf(timeOut[1]);

    int diff = 0;
    if (outMinutes > inMinutes) {
        diff = outMinutes - inMinutes;
    } else if (outMinutes < inMinutes) {
        diff = outMinutes + 24 * 60 - inMinutes;
    }

    System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut, diff / 60, diff % 60);
}

更新
这是一个基于LocalTimeDuration

的解决方案
public static void calcTime2(String sTimeIn, String sTimeOut) {
    final String timePattern = "[0-2][0-9]:[0-5][0-9]";

    if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
        throw new IllegalArgumentException();
    }

    String[] timeIn = sTimeIn.split(":");
    String[] timeOut = sTimeOut.split(":");

    LocalTime localTimeIn = LocalTime.of(Integer.valueOf(timeIn[0]), Integer.valueOf(timeIn[1]));
    LocalTime localTimeOut = LocalTime.of(Integer.valueOf(timeOut[0]), Integer.valueOf(timeOut[1]));

    Duration duration;
    if (localTimeOut.isAfter(localTimeIn)) {
        duration = Duration.between(localTimeIn, localTimeOut);
    } else {
        Duration prevDay = Duration.ofHours(24).minusHours(localTimeIn.getHour()).minusMinutes(localTimeIn.getMinute());
        Duration nextDay = Duration.between(LocalTime.MIDNIGHT, localTimeOut);
        duration = prevDay.plus(nextDay);
    }

    System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut,
            duration.toHours(), duration.minusHours(duration.toHours()).toMinutes());     
}

答案 3 :(得分:0)

尝试:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
   //Read data
   System.out.println("Clock In: ");
   String sTimeIn = "20:30";

   System.out.println("Clock Out: ");
   String sTimeOut = "18:20";

   // Process data
   String sHourIn = sTimeIn.substring(0, 2);
   String sMinuteIn = sTimeIn.substring(3, 5);
   String sHourOut = sTimeOut.substring(0, 2);
   String sMinuteOut = sTimeOut.substring(3, 5);

   int iHourIn = Integer.parseInt(sHourIn);
   int iMinuteIn = Integer.parseInt(sMinuteIn);
   int iHourOut = Integer.parseInt(sHourOut);
   int iMinuteOut = Integer.parseInt(sMinuteOut);

   Calendar cal = Calendar.getInstance();

   cal.set(Calendar.HOUR_OF_DAY,iHourIn);
   cal.set(Calendar.MINUTE,iMinuteIn);
   cal.set(Calendar.SECOND,0);
   cal.set(Calendar.MILLISECOND,0);
   Long timeIn = cal.getTime().getTime();

   cal.set(Calendar.HOUR_OF_DAY,iHourOut);
   cal.set(Calendar.MINUTE,iMinuteOut);
   cal.set(Calendar.SECOND,0);
   cal.set(Calendar.MILLISECOND,0);
   Long timeOut = cal.getTime().getTime();

   Long finaltime=  timeIn-timeOut;

   // Convert the result to Hours and Minutes

   Long temp = null;
   // get hours
   temp = finaltime % 3600000 ;
   int sumHour = (int) ((finaltime - temp) / 3600000 );

   finaltime = temp;

   int sumMinute = (int) (finaltime/ 60000);

   //Display Output
   System.out.println(sumHour +" Hour "+ sumMinute + " Minute");
}   

答案 4 :(得分:-1)

除了您的代码外,我还添加了一些代码。请检查并告诉我是否满足您的要求

public class MainClass1 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //Read data
    System.out.print("Clock In: ");
    String[] sTimeIn = input.nextLine().split(":");

    System.out.print("Clock Out: ");
    String[] sTimeOut = input.nextLine().split(":");

    int iHourIn = Integer.parseInt(sTimeIn[0]);
    int iMinuteIn = Integer.parseInt(sTimeIn[1]);
    int iHourOut = Integer.parseInt(sTimeOut[0]);
    int iMinuteOut = Integer.parseInt(sTimeOut[1]);

    if(iMinuteIn < iMinuteOut) {
        iMinuteIn = 60 + iMinuteIn;
        iHourIn--;
    }
    int sumHour = iHourIn - iHourOut;
    int sumMinute = iMinuteIn - iMinuteOut;

            //Display Output
            System.out.print(sumHour +"Hour "+ sumMinute + " Minute");


    }
}
相关问题