Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Military Time Difference in Java

Tags:

java

Here's my TimeInterval class:

public class TimeInterval {

   private int fTime;
   private int sTime;

   public TimeInterval(int fTime, int sTime) {
      if(fTime < 0 || fTime > 2400 || sTime < 0 || sTime > 2400) {
          System.out.println("Illegal times, must be < 2400 and > 0)");
          System.exit(0);
      } else {
          this.fTime = fTime;
          this.sTime = sTime;
      }
   }

   public int getHours() {
      return Math.abs((fTime - sTime) / 100);
   }

   public int getMinutes() {
       return Math.abs((fTime - sTime) % 100);
   }

   public double getDecimalTime() {
      return getHours() + ((double) getMinutes() / 60);
   }
}

and my tester class:

import java.util.*;

public class TestTimeInterval {

   public static void main(String[] args) {

      Scanner s = new Scanner(System.in);
      System.out.print("Please enter the first time: ");
      int fTime = s.nextInt();
      System.out.print("Please enter the second time: ");
      int sTime = s.nextInt();

      TimeInterval t = new TimeInterval(fTime, sTime);

      System.out.printf("%s: %2d hours %2d minutes \n", "Elapsed time in hrs/min ", t.getHours(), t.getMinutes());
      System.out.printf("%s: %.2f", "Elapsed time in decimal", t.getDecimalTime());

   }    
}

However, it calculates certain time correctly, but if I enter for example 0150 and 0240, the difference should be 50 minutes, but instead it displays 90, and I need to make it not go over 60, and transform the remainder to hours and minutes. While if I enter some other numbers, it works. Any help is appreciated.

like image 466
dynamitem Avatar asked Oct 11 '18 18:10

dynamitem


People also ask

How do you convert time to military time?

To convert from standard time to military time, simply add 12 to the hour. So, if it's 5:30 p.m. standard time, you can add 12 to get the resulting 1730 in military time. To convert from military time to standard time, just subtract 12 from the hour.

How do you convert time in Java?

mport java. util. Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int days=24; int hours = 60; int mins=60; int res=days*hours*mins; System.

What are time and time class in Java?

As the name suggests, they store hours, minutes and seconds of a given time respectively. The Time class has a constructor that initializes the value of hours, minutes, and seconds. We've also created a static function difference that takes two Time variables as parameters, find the difference and returns it as Time class.

How to use date and time in Java?

Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example: Class. Description. LocalDate. Represents a date (year, month, day (yyyy-MM-dd)) LocalTime. Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))

How to get the difference in hours and minutes in Java?

Java has brought a ton of features in the 8th JDK version and few of them are the LocalTime and ChronoUnit classes present in the java.time package. LocalTime object parses the date in the format HH:MM:SS and ChronoUnit is used to get the difference in hours, minutes and seconds. Below is the code for the above approach:

How do I compare two DateTime objects in Java?

Date comparison is required when we want to get the data of some specific date and time from the database or to filter the returned data based on date and time. In order to compare time, we use the compareTo () method of the LocalTime class. The compareTo () method of the class compares two LocalTime objects.


1 Answers

tl;dr

Duration
.between(
    LocalTime.parse( "0150" , DateTimeFormatter.ofPattern( "HHmm" ) ) ,
    LocalTime.parse( "0240" , DateTimeFormatter.ofPattern( "HHmm" ) ) 
)
.toString()

PT50M

Details

Perhaps you are just working on homework. If so, make that clear in your Question.

But you should know that Java provides classes for this purpose.

java.time

The modern approach uses the java.time classes. These classes work in 24-hour clock by default.

LocalTime

For a time-of-day without a date and without a time zone, use LocalTime.

    LocalTime start = LocalTime.of( 1 , 50 );
    LocalTime stop = LocalTime.of( 2 , 40 );

Duration

Calculate elapsed time as a Duration.

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

Generate text representing that Duration value. By default, standard ISO 8601 format is used.

    System.out.println( d );

PT50M

Parts

You can extract the parts if desired.

int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;

Parsing

To parse your HHMM format provided by your users, use DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "HHmm" ) ;
LocalTime lt = LocalTime.parse( "0150" , f ) ;

Zones

Be aware that working only with time-of-day without the context of date and time zone can lead to incorrect results. If working in UTC, no problem. But if your time-of-day values are actually intended to represent the wall-clock time of a particular region, then anomalies such as Daylight Saving Time (DST) will be ignored by use of LocalTime only. In your example, there may be no two o'clock hour, or two o'clock have have been repeated, if occurring on a DST cut-over date in the United States.

If you implicitly intended a time zone, make that explicit by applying a ZoneId to get a ZonedDateTime object.

LocalDate ld = LocalDate.of( 2018 , 1 , 23 ) ;
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
…
Duration d = Duration.between( zdt , laterZdt ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 162
Basil Bourque Avatar answered Sep 20 '22 16:09

Basil Bourque