snmln
snmln

Reputation: 3

How to transfer Date.getTime() to hours and calculating difference

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?

Upvotes: 0

Views: 327

Answers (2)

John Camerin
John Camerin

Reputation: 722

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

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

Use the latest classes available fron java8

LocalDateTime now = LocalDateTime.now();
System.out.println(now.getHour());

Upvotes: 1

Related Questions