How do I calculate time difference in Java?

Kevin

So I am currently working on a project and I have a method which is suppose to help me calculate the working hours of employees based on a simple formula which is work hours = logout - login - break.

For some reason best known to my computer, the value of my break time gets reduced by 1 all the time. Can anyone please let me know why this is happening and how I can resolve it? Thanks

public String calculateHoursWorked() throws ParseException {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your login time:");
    loginTime = sc.nextLine();
    System.out.println("Please enter your break duration:");
    breakTime = sc.nextLine();
    System.out.println("Please enter your logout time:");
    logoutTime = sc.nextLine();

    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    Date login = format.parse(loginTime);
    Date logout = format.parse(logoutTime);
    Date breakPeriod = format.parse(breakTime);

    //calculate the total number of hours worked in a day
    long totalHoursWorked = logout.getTime() - login.getTime() - breakPeriod.getTime();

    //get the breaktime in milliseconds to make sure we have the right value here
    long breakTimeinMilliseconds = breakPeriod.getTime();
    System.out.println("So our break time is ms is: "+ breakTimeinMilliseconds);
    String test = DurationFormatUtils.formatDuration(breakTimeinMilliseconds,"HH:mm");
    System.out.println("Your break time is: " + test);


    return DurationFormatUtils.formatDuration(totalHoursWorked, "HH:mm");

    //return String.valueOf(logout.getTime() - (login.getTime() + break_Period.getTime()));

}

This is the output I get on my console:

Please enter your login time:
02:00
Please enter your break duration:
**02:00**
Please enter your logout time:
10:00
So our break time is ms is: 3600000
**Your break time is: 01:00** (entered 02:00 above but I get 01:00 here)
Your working time is: 07:00 ***(This has to be 6)***
meriton

The Javadoc of Date says:

The class Date represents a specific instant in time, with millisecond precision.

and

public long getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Hm, so which Timezone is the SimpleDateFormatter using? It's Javadoc says:

public SimpleDateFormat(String pattern)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale.

(emphasis mine)

The default locale is the default locale set in your computer's operating system.

So your program:

    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    Date breakPeriod = format.parse(breakTime);
    long breakTimeinMilliseconds = breakPeriod.getTime();

asks the computer to interpret the text as an instant in time using the default time zone of your computer. Your computer therefore interprets "02:00" as two hours after midnight, Central European Time. Then, you ask how long after midnight, GMT, that was. The computer knows that 02:00 CET is 01:00 GMT, so answers 3600000. That is, in using a class intended to represent instants in time with respect to some timezone, and using methods that default to different time zones, your code managed to accidentally convert between time zones :-)

Because the Date class is prone to such programming mistakes, it has been superseeded by a new date and time api, which you can find in the package java.time. Using that package, you can write:

var login = LocalTime.parse("08:00");
var breakDuration = Duration.between(LocalTime.MIDNIGHT, LocalTime.parse("02:00"));
var logout = LocalTime.parse("18:00");
        
var workDuration = Duration.between(login, logout).minus(breakDuration);
var workDurationString = LocalTime.MIDNIGHT.plus(workDuration).toString();

(if you wish to be more lenient in parsing / formatting, or use a different format, you may want to use a DateTimeFormatter, possibly obtained from a DateTimeFormatterBuilder, instead)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I calculate time difference in AngularJS?

How Do I calculate the difference of 2 time zones in JavaScript?

How do I calculate the difference between two time values in Excel?

How to calculate time difference in java?

How do I calculate the elapsed time of an event in java?

How do i calculate the time complexity of this function?

How do I calculate the time intervals (PHP)?

How do I calculate the time complexity of this algorithm?

How do I properly calculate this time complexity

Java calculate time difference error

Calculate date/time difference in java

java script calculate time difference

How can I calculate difference between two dates with time in minutes

How to calculate the difference between two java.sql.Time values?

How to calculate the time difference in seconds?

How to calculate the time difference in Laravel

How to calculate time difference in MySQL?

How to calculate the ID time difference

How do I calculate the average difference between two dates in Django?

How do I calculate the difference of two angle measures?

How Do I Calculate The Difference of Each Element in A List (Python)

How do I calculate the year difference in my programm?

How do I calculate the difference between two timestamps?

How do I calculate the difference between two dates?

How do I calculate day on day difference in a pandas dataframe

How do I calculate the difference of times from three text boxes?

How do I calculate the difference of two alias for sorting

How do I calculate the difference between and percentile of properties?

How do you I calculate the difference between two timestamps in PostgreSQL?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive