Military Time Difference in Java

  • A+
Category:Languages

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.

Thanks in advance!

 


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?

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: