How to add two milliseconds to android

I want to calculate the difference between two times, which calculates correctly, then I need to do it in half, so I divide it by 2 results. but when i try to add timdedifferencemillis to startTime it doesn't give me correct result ...

starttime = 05:53
endtime = 17:57
i want 11:55 results
but my code gives me 06:55
please help .....

protected String transitTime2(String endtime, String starttime) {
    SimpleDateFormat dt = new SimpleDateFormat("hh:mm");
    Date startTime = null;
    Date endTime;
    long timdedifferencemillis = 0;
    try {
        startTime = dt.parse(starttime);
        endTime = dt.parse(endtime);
        long diff=startTime.getTime();
        timdedifferencemillis = (endTime.getTime() - startTime.getTime())/2;
        //timdedifferencemillis

    } catch (ParseException e) {
        e.printStackTrace();
    }
    long timdedifferencemillis1=startTime.getTime()+timdedifferencemillis;

    int minutes = Math
            .abs((int) ((timdedifferencemillis1 / (1000 * 60)) % 60));
    int hours = Math
            .abs((int) ((timdedifferencemillis1 / (1000 * 60 * 60)) % 24));
    String hmp = String.format("%02d %02d ", hours, minutes);
    return hmp;
}

      

+3


source to share


3 answers


The problem is probably in the time zone; when you first parse endtime

and starttime

, by default (in the absence of an explicit time zone specified in the format string and provided in the input), Java assumes that the times provided are relative to the local time zone of the system. Then when you call getTime()

it returns

the number of milliseconds since Jan 1, 1970 00:00:00 GMT represented by this objectDate



One solution is to tell your object to SimpleDateFormat

assume that all the strings it parses are in GMT and not in your local timezone. Try adding this line after initialization dt

, but before calling dt.parse(...)

:

dt.setTimeZone(TimeZone.getTimeZone("GMT"));

      

+2


source


I think the problem is the "long" and "int" types in your code, when we divide by 2 (long timdedifferencemillis), the result should be "double".



0


source


It's pretty easy to do it with the new API java.time

in Java 8, or with the JODA timing library:

import java.time.Duration;
import java.time.LocalTime;

public class TimeDiff {
    public static void main(String[] args) {
        LocalTime start = LocalTime.parse("05:53");
        LocalTime end = LocalTime.parse("17:57");
        // find the duration between the start and end times
        Duration duration = Duration.between(start, end);
        // add half the duration to the start time to find the midpoint
        LocalTime midPoint = start.plus(duration.dividedBy(2));
        System.out.println(midPoint);
    }
}

      

Output:

11:55

By using objects LocalTime

, you avoid time zone problems.

0


source







All Articles