Java 爪哇军时的时差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21153746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:57:42  来源:igfitidea点击:

time difference in military time in Java

javatime

提问by Nathan Curtis

So for an assignment we had to write a program that takes two times in military time and shows the difference in hours and minutes between them assuming the first time is the earlier of the two times. We weren't allowed to use if statements as it technically has not be learned. Here's an example of what it'd look like run. In quotes I'll put what is manually entered when it is prompted to.

因此,对于一项作业,我们必须编写一个程序,该程序需要两次军用时间,并假设第一次是两次中较早的时间,并显示它们之间的小时和分钟差异。我们不被允许使用 if 语句,因为它在技术上还没有被学习。这是运行的示例。在引号中,我会在提示时输入手动输入的内容。

java MilitaryTime

Please enter first time:  "0900"

Please enter second time:  "1730"

8 hours 30 minutes    (this is the final answer)

I was able to quite easily get this part done with the following code:

我可以很容易地使用以下代码完成这部分工作:

class MilitaryTime  {

   public static void main(String [] args) {

      Scanner in = new Scanner(System.in);

            System.out.println("Please enter the first time: ");

            int FirstTime = in.nextInt();

            System.out.println("Please enter the second time: ");

            int SecondTime = in.nextInt();

            int FirstHour = FirstTime / 100;

            int FirstMinute = FirstTime % 100;

            int SecondHour = SecondTime / 100;

            int SecondMinute = SecondTime % 100;

            System.out.println( ( SecondHour - FirstHour ) + " hours " + ( SecondMinute 

                - FirstMinute ) + " minutes "  );
       }
}

Now my question is something wasn't assigned (or I wouldn't be here!) is there's another part to this question in the book that says to take that program we just wrote and deal with the case where the first time is later than the second. This has really intrigued me about how this would be done and has really stumped me. Again we aren't allowed to use if statements or this would be easy we basically have all the mathematical functions to work with.

现在我的问题是有些东西没有被分配(或者我不会在这里!)书中是否还有另一个部分说要使用我们刚刚编写的程序并处理第一次晚于的情况第二。这真的让我对如何做到这一点很感兴趣,也让我很难过。同样,我们不允许使用 if 语句,否则这很容易,我们基本上可以使用所有数学函数。

An example would be the first time is now 1730 and the second time is 0900 and so now it returns 15 hours 30 minutes.

一个例子是第一次现在是 1730,第二次是 0900,所以现在它返回 15 小时 30 分钟。

采纳答案by Zaw Than oo

I would like to suggest to use org.joda.time.DateTime. There are a lot of date and time functions.

我想建议使用org.joda.time.DateTime。有很多日期和时间函数。

Example :

例子 :

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = format.parse("10-05-2013 09:00");
Date endDate = format.parse("11-05-2013 17:30");

DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);

int years = Years.yearsBetween(jdStartDate, jdEndDate).getYears();
int days = Days.daysBetween(jdStartDate, jdEndDate).getDays();
int months =  Months.monthsBetween(jdStartDate, jdEndDate).getMonths();
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();

System.out.println(hours + " hours " + minutes + " minutes");

Your expected program will be as below :

您的预期程序如下:

SimpleDateFormat format = new SimpleDateFormat("hhmm");
Dates tartDate = format.parse("0900");
Date endDate = format.parse("1730");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
minutes = minutes % 60;

System.out.println(hours + " hours " + minutes + " minutes");

Output :

输出 :

8 hours 30 minutes

回答by Jeremy Bader

I would do something like:

我会做这样的事情:

System.out.println(Math.abs( SecondHour - FirstHour ) + " hours " + Math.abs( SecondMinute - FirstMinute ) + " minutes "  );

The absolute value will give you the difference between the two times as a positive integer.

绝对值将为您提供两次之间的差值作为正整数。

回答by takendarkk

You could do something like this

你可以做这样的事情

//Code like you already have
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();

//Now we can continue using the code you already wrote by
//forcing the smaller of the two times into the 'firstTime' variable.
//This forces the problem to be the same situation as you had to start with
if (secondTime < firstTime) {
    int temp = firstTime;
    firstTime = secondTime;
    secondTime = temp;
}

//Continue what you already wrote

There are many other ways but this was something I used for similar problems while learning. Also, note that I changed variable names to follow java naming conventions - variables are lowerCamelCase.

还有很多其他方法,但这是我在学习时用于解决类似问题的方法。另外,请注意,我更改了变量名称以遵循 java 命名约定 - 变量是小驼峰式的。

回答by MadProgrammer

Normally, when dealing with time calculations of this nature I would use Joda-Time, but assuming that you don't care about the date component and aren't rolling over the day boundaries, you could simply convert the value to minutes or seconds since midnight...

通常,在处理这种性质的时间计算时,我会使用 Joda-Time,但假设您不关心日期组件并且不跨越日期边界,您可以简单地将值转换为分钟或秒午夜...

Basically the problem you have is the simple fact that there are 60 minutes in an hour, this makes doing simple mathematics impossible, you need something which is more common

基本上你遇到的问题是一个简单的事实,即一小时有 60 分钟,这使得做简单的数学变得不可能,你需要一些更常见的东西

For example, 0130is actually 90 minutes since midnight, 1730is 1050 minutes since midnight, which makes it 16 hours in difference. You can simply subtract the two values to get the difference, then convert that back to hours and minutes...for example...

例如,0130实际距午夜 90 分钟,距午夜17301050 分钟,因此相差 16 小时。您可以简单地减去两个值以获得差异,然后将其转换回小时和分钟......例如......

public class MilTimeDif {

    public static void main(String[] args) {
        int startTime = 130;
        int endTime = 1730;
        int startMinutes = minutesSinceMidnight(startTime);
        int endMinutes = minutesSinceMidnight(endTime);

        System.out.println(startTime + " (" + startMinutes + ")");
        System.out.println(endTime + " (" + endMinutes + ")");

        int dif = endMinutes - startMinutes;

        int hour = dif / 60;
        int min = dif % 60;

        System.out.println(hour + ":" + min);

    }

    public static int minutesSinceMidnight(int milTime) {
        double time = milTime / 100d;

        int hours = (int) Math.floor(time);
        int minutes = milTime % 100;

        System.out.println(hours + ":" + minutes);

        return (hours * 60) + minutes;
    }

}

Once you start including the date component or rolling over day boundaries, get Joda-Time out

一旦您开始包含日期组件或跨越日期边界,请退出 Joda-Time

回答by fymo

import java.util.Scanner;

 public class TimeDifference{

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    // read first time
    System.out.println("Please enter the first time: ");
    int firstTime = in.nextInt();

    // read second time
    System.out.println("Please enter the second time: ");
    int secondTime = in.nextInt();

    in.close();

    // if first time is more than second time, then the second time is in
    // the next day ( + 24 hours)
    if (firstTime > secondTime)
        secondTime += 2400;

    // first hour & first minutes
    int firstHour = firstTime / 100;
    int firstMinute = firstTime % 100;

    // second hour & second minutes
    int secondHour = secondTime / 100;
    int secondMinute = secondTime % 100;

    // time difference
    int hourDiff = secondHour - firstHour;
    int minutesDiff = secondMinute - firstMinute;

    // adjust negative minutes
    if (minutesDiff < 0) {
        minutesDiff += 60;
        hourDiff--;
    }

    // print out the result
    System.out.println(hourDiff + " hours " + minutesDiff + " minutes ");

 }
}

回答by Mikeniad28

import java.util.*;

class Time
{
    static Scanner in=new Scanner(System.in);
    public static void main(String[] args)
    {
        int time1,time2,totalTime;
        System.out.println("Enter the first time in military:");
        time1=in.nextInt();
        System.out.println("Enter the second time in military:");
        time2=in.nextInt();
        totalTime=time2-time1;
        String temp=Integer.toString(totalTime);
        char hour=temp.charAt(0);
        String min=temp.substring(1,3);
        System.out.println(hour+" hours "+min+" minutes");
    }
}

回答by Mikeniad28

This one is done without using ifs and date thingy. you just need to use integer division "/", integer remainder thing"%", and absolute value and celing. might be able to be simplified but im too lazy at moment. I struggled for hours to figure out and seems nobody else got the answer without using more advanced functions. this problem was in Cay Horstmann's Java book. Chapter 4 in Java 5-6 version of the book "Java Concepts"

这是在不使用 ifs 和 date thingy 的情况下完成的。你只需要使用整数除法“/”,整数余数“%”,以及绝对值和celing。也许可以简化,但我现在太懒了。我挣扎了几个小时才弄清楚,似乎没有其他人在不使用更高级的功能的情况下得到了答案。这个问题出现在 Cay Horstmann 的 Java 书中。Java 5-6 版《Java 概念》一书的第 4 章

import java.util.Scanner;

public class MilitaryTime {

    public static void main (String[] args){

        //creates input object
        Scanner in = new Scanner(System.in);

        System.out.println("Enter time A: ");
        String timeA = in.next();

        System.out.println("Enter time B: ");
        String timeB = in.next();

        //Gets the hours and minutes of timeA
        int aHours = Integer.parseInt(timeA.substring(0,2));
        int aMinutes = Integer.parseInt(timeA.substring(2,4));

        //Gets the hours and minutes of timeB
        int bHours = Integer.parseInt(timeB.substring(0,2));
        int bMinutes = Integer.parseInt(timeB.substring(2,4));

        //calculates total minutes for each time
        int aTotalMinutes = aHours * 60 + aMinutes;
        int bTotalMinutes = bHours * 60 + bMinutes;


       //timeA>timeB: solution = (1440minutes - (aTotalMinutes - bTotalMinutes))
       //timeA<timeB: solution is (bTotalMinutes - aTotalMinutes) or   
       //-(aTotalMinutes - bTotalMinutes)
       //we need 1440 term when  timea>timeeB... we use mod and mod remainder

        //decider is 1 if timeA>timeB and 0 if opposite.
        int decider = ((aTotalMinutes - bTotalMinutes +1440)/1440);
        // used 4 Special case when times are equal. this way we get 0
        // timeDiffference term when equal and 1 otherwise.

        int equalsDecider = (int) Math.abs((aTotalMinutes - bTotalMinutes));

        //fullDayMaker is used to add the 1440 term when timeA>timeB
        int fullDayMaker = 1440 * decider;
        int timeDifference = (equalsDecider)* (fullDayMaker - (aTotalMinutes - bTotalMinutes));

        // I convert back to hours and minmutes using modulater
        System.out.println(timeDifference/60+" hours and "+timeDifference%60+" minutes");
    }
}

回答by Basil Bourque

java.time

时间

Java 8 and later includes the new java.timeframework. See the Tutorial.

Java 8 及更高版本包含新的java.time框架。请参阅教程

The new classes include LocalTimefor representing a time-only value without date and without time zone.

新类包括LocalTime用于表示没有日期和时区的仅时间值。

Another class is Duration, for representing a span of time as a total number of seconds and nanoseconds. A Durationmay be viewed as a number of hours and minutes.

另一个类是Duration,用于将时间跨度表示为总秒数和纳秒数。ADuration可被视为小时数和分钟数。

By default the Durationclass implements the toStringmethod to generate a String representation of the value using the ISO 8601 formatof PnYnMnDTnHnMnSwhere the Pmarks the beginning and the Tseparates the date portion from the time portion. The Durationclass can parse as well as generate strings in this standard format.

默认情况下,Duration该类实现了toString使用ISO 8601 格式生成值的字符串表示形式的方法PnYnMnDTnHnMnS其中P标记开始并将T日期部分与时间部分分开。本Duration类可以解析以及生成此标准格式字符串。

So, the result in example code below is PT8H30Mfor eight and a half hours. This format is more sensible than 08:30which can so easily be confused for a time rather than a duration.

因此,下面示例代码中的结果是PT8H30M八个半小时。这种格式比08:30很容易混淆一段时间而不是持续时间的格式更明智。

String inputStart = "0900";
String inputStop = "1730";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HHmm" );;

LocalTime start = formatter.parse ( inputStart , LocalTime :: from );
LocalTime stop = formatter.parse ( inputStop , LocalTime :: from );

Duration duration = Duration.between ( start , stop );

Dump to console.

转储到控制台。

System.out.println ( "From start: " + start + " to stop: " + stop + " = " + duration );

When run.

跑的时候。

From start: 09:00 to stop: 17:30 = PT8H30M

从开始:09:00 到停止:17:30 = PT8H30M

回答by BumKneesOhYeah

I used 3 classes. Lets go over theory first.

我使用了 3 个类。让我们先回顾一下理论。

We have two times: A and B.

我们有两次:A 和 B。

  • if AtimeDiff = (B-A).....which can be written -(A-B)
  • if A>B, then timeDiff = 1440- (A-B)[1440 is total minutes in day]
  • if AtimeDiff = (BA).....可以写成 -(A-B)
  • 如果 A>B,则timeDiff = 1440- (A-B)[1440 是一天中的总分钟数]

Thus we need to make timeDiff = 1440 - (A-B)and we need to make 1440 term dissapear when A

因此,timeDiff = 1440 - (A-B)当 A 时,我们需要使 1440 项消失

Lets make a term X = (A-B+1440) / 1440(notice "/" is integer division.

让我们做一个术语X = (A-B+1440) / 1440(注意“/”是整数除法。

  • 'if A
  • 'if A>B then X = 1;
  • '如果一个
  • '如果 A>B 则 X = 1;

Now look at a new term Y = 1440 * X.

现在看一个新术语Y = 1440 * X

  • 'if A
  • 'if A>B then Y = 1440'.
  • '如果一个
  • '如果 A>B 那么 Y = 1440'。

PROBLEM SOLVED. Now just plug into Java Programs. Note what happens if A=B. Our program will assume we know no time passes if times are exact same time. It assumes that 24 hours have passed. Anyways check out the 3 programs listed below:

问题解决了。现在只需插入 Java 程序即可。注意如果 A=B 会发生什么。如果时间完全相同,我们的程序将假设我们知道时间不会过去。它假设已经过去了 24 小时。无论如何,请查看下面列出的 3 个程序:

Class #1

第 1 类

    public class MilitaryTime {
    /**
     * MilitaryTime A time has a certain number of minutes passed at 
     *              certain time of day.
     * @param milTime The time in military format
    */
    public MilitaryTime(String milTime){
        int hours = Integer.parseInt(milTime.substring(0,2));
        int minutes = Integer.parseInt(milTime.substring(2,4));
        timeTotalMinutes = hours * 60 + minutes;

    }
    /**
     * Gets total minutes of a Military Time
     * @return gets total minutes in day at certain time
     */
    public int getMinutes(){
        return timeTotalMinutes;
    }

    private int timeTotalMinutes;   
    }

Class#2

班级#2

 public class TimeInterval {

/**
  A Time Interval is amount of time that has passed between two times
  @param timeA first time
  @param timeB second time
*/
public TimeInterval(MilitaryTime timeA, MilitaryTime timeB){

    // A will be shorthand for timeA and B for timeB
    // Notice if A<B timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B)
    // Notice if A>B timeDifferential = - (A - B)
    // Both will use timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B),
    //  but we need to make TOTAL_MINUTES_IN_DAY dissapear when needed


    //Notice A<B following term "x" is 1 and if A>B then it is 0.
    int x = (timeA.getMinutes()-timeB.getMinutes()+TOTAL_MINUTES_IN_DAY)
             /TOTAL_MINUTES_IN_DAY;
    // Notice if A<B then  term "y" is TOTAL_MINUTES_IN_DAY(1440 min) 
    // and if A<B it is 0
    int y = TOTAL_MINUTES_IN_DAY * x;
    //yay our TOTAL_MINUTES_IN_DAY dissapears when needed.

    int timeDifferential = y - (timeA.getMinutes() - timeB.getMinutes());
    hours = timeDifferential / 60;
    minutes = timeDifferential % 60;

    //Notice that if both hours are equal, 24 hours will be shown.
    //  I assumed that we would knoe if something start at same time it
    //   would be "0" hours passed

}
/**
 * Gets hours passed between 2 times
 * @return hours of time difference 
 */
public int getHours(){
    return hours;
}

/**
 * Gets minutes passed after hours accounted for
 * @return minutes remainder left after hours accounted for
 */ 
public int getMinutes(){
    return minutes;
}

private int hours;
private int minutes;
public static final int TOTAL_MINUTES_IN_DAY = 1440;//60minutes in 24 hours

}

Class#3

班级#3

import java.util.Scanner;

public class MilitaryTimeTester {
    public static void main (String[] args){

        Scanner in = new Scanner(System.in);

        System.out.println("Enter time A: ");
        MilitaryTime timeA = new MilitaryTime(in.nextLine());

        System.out.println("Enter time B: ");
        MilitaryTime timeB = new MilitaryTime(in.nextLine());

        TimeInterval intFromA2B = new TimeInterval(timeA,timeB);

        System.out.println("Its been "+intFromA2B.getHours()+" hours and "+intFromA2B.getMinutes()+" minutes.");   
    }
}