0

I have a program that is intaking an "AM" "PM" time and calculating out the hours in the day equivalent (in 24 hour format). For some reason it parses and calculates the time I input to the incorrect 24 hour equivalent (ie 5:00 pm comes to equal 22)

System.out.print("Enter the end time (HH:MM am): ");
endTime = input.nextLine();
Date ETime = time_to_date.parse(endTime);

Class method

public int get_Family_A_Calulation(Date STime, Date ETime) {
    Date startTimeCalc = STime, endTimeCalc = ETime;
    int pay = 0, hoursWorked, StartHour, EndHour;
    StartHour = ((((int) startTimeCalc.getTime()) / 1000) / 60) / 60;
    EndHour = ((((int) endTimeCalc.getTime()) / 1000) / 60) / 60;
    pay = hoursWorked * 15;
    return pay;
}

I am not sure where my error is can anyone give me advice on how to correct this error?

snmln
  • 3
  • 2
  • why are you casting to `int` ? – Scary Wombat Nov 22 '18 at 02:33
  • Consider this code `Date now = new Date (); System.out.println(now.getTime()); System.out.println(((int)now.getTime()));` – Scary Wombat Nov 22 '18 at 02:34
  • @ScaryWombat The reason I am casting to an int is because I am going to need to do payroll calculation based on a start and end time input. The rate per hour changes depending on what hour of the day the individual works. 5pm-11pm per hour rate is $15 and any time after 11pm the rate changes to $20. So I have a few if statements later in the program where all the calculations are based of off a 24 hour calculations in int form. – snmln Nov 22 '18 at 14:46
  • Possible duplicate of [Java: getMinutes and getHours](https://stackoverflow.com/questions/907170/java-getminutes-and-gethours) – Ole V.V. Nov 22 '18 at 19:59

2 Answers2

1

Use the latest classes available fron java8

LocalDateTime now = LocalDateTime.now();
System.out.println(now.getHour());
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

The actual data behind Date is milliseconds since the epoch. Any hour or time representation is based on the calendar date portion and takes into account timezone and daylight savings. Regardless of what you do, there will be calculation issues across days, etc. As suggested by Scary Wombat, use the new classes in java.time package. For your specific case, you need a LocalTime as the code is trying to represent a time element (hours, minutes, seconds, etc) without consideration for Date, TimeZone, etc. https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html

John Camerin
  • 677
  • 5
  • 15