Time calculation with negative value results Java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Time calculation with negative value results Java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to calculate the difference between a start time and an end time. In HH:mm format.

I receive a negative value when, for example, the start time is 22.00 and the end time is 1.00 the next day.

How do I let the program know the end time is on the next day?

My script:

public void setBeginTijd()
{
    String dateStart = "22:00";
    String dateEnd = "1:00";

    SimpleDateFormat format = new SimpleDateFormat("HH:mm");

    Date d1 = null;
    Date d2 = null;

    try
    {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateEnd);

        long diff = d2.getTime() - d1.getTime();
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;

        System.out.println(diffMinutes);
        System.out.println(diffHours);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

Answer

As already mentioned by some people, it is important to also know day, month and year of each event to calculate periods for events that are not on the same day.

I modified your method the way I think it could help you:

public void setBeginTijd()
{
        String dateStart = "22.08.2014 22:00";
        String dateEnd = "25.08.2014 01:00";

        SimpleDateFormat fullFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");

        Date d1 = null;
        Date d2 = null;

        try
        {
            d1 = fullFormat.parse(dateStart);
            d2 = fullFormat.parse(dateEnd);

            long diff = d2.getTime() - d1.getTime();
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            System.out.println("Delta minutes: " + diffMinutes);
            System.out.println("Delta hours: " + diffHours);
            System.out.println("Delta days: " + diffDays);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
}
We are here to answer your question about Time calculation with negative value results Java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji