Java / Android - Calculate difference between timestamps [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-13 15:39:23

问题


I have a problem figuring out how to calculate the elapsed time between two timestamps (hours, minutes, seconds). This is the result:

String starttime = beginElement.getTimestamp();
String endtime = element.getTimestamp();

I/Start time: 1496258892612

I/End time: 1496258928999

long diffTime = Long.parseLong(endtime) - Long.parseLong(starttime);

I/Diff time: 36387

String elapsedtime = new SimpleDateFormat("hh:mm:ss").format(Long.parseLong(String.valueOf(diffTime)));

I/Elapsed time: 01:00:36

In fact, the elapsed time is just 36 seconds. It's always one hour less than the result.

How do I fix this strange issue?


回答1:


you are using the API incorrectly, parse is not what you need since that time is not related to a date but to a duration period instead....

do something like:

String periodAsHH_MM_SS = String.format("%02d:%02d:%02d", 
        TimeUnit.MILLISECONDS.toHours(diffTime),
        TimeUnit.MILLISECONDS.toMinutes(diffTime) % TimeUnit.HOURS.toMinutes(1),
        TimeUnit.MILLISECONDS.toSeconds(diffTime) % TimeUnit.MINUTES.toSeconds(1));

System.out.println("Duration in hh:mm:ss is: "+periodAsHH_MM_SS);



回答2:


You need to set GMT timezone, try this:

    SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");
    sd.setTimeZone(TimeZone.getTimeZone("GMT"));
    String elapsedtime = sd.format(diff);


来源:https://stackoverflow.com/questions/44341891/java-android-calculate-difference-between-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!