How to Convert Negative Milliseconds at the Right TimeZone in Java

I work with Java dates, I can not get out of this problem. In my file, the value of Time is saved as (HH: MM: SS)

00:00:08 below is the code and output.

String timeinsec = "00:00:08"; DateFormat df = new SimpleDateFormat("hh:mm:ss"); Date time = df.parse(timeinsec); 

What happened when I assigned variable values ​​and time. time.fastTime variable show "-17992000"

when I convert this value to HH: MM: SS shows me. "-4: -59: -51"

Anyone can help fix TimeZone problem. Current time zone: GMT + 5

+4
source share
4 answers

Try it;

 int day = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); 
+3
source

here is the reverse code:

 Date new_time = Time_array.get(0).time; //-17992000 stored in "fastTime" variable long diff = ((long)new_time.getTime()); //TimeUnit.MILLISECONDS long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; String hms = String.format("%d:%02d:%02d", diffHours, diffMinutes, diffSeconds); 

in dubug: hms value = -4: -59: -51

+2
source

I tried in many ways, so finally I wrote this code and my requirement is met.

 Calendar cal = Calendar.getInstance(); String timeinsec = "00:00:08"; DateFormat df = new SimpleDateFormat("hh:mm:ss"); Date time = df.parse(timeinsec); cal.setTime(time); hms = String.format("%d:%02d:%02d", cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); 

Result: 00:00:08

+2
source

hh is 1 ~ 12. You should use HH (0 ~ 23)

 String timeinsec = "00:00:08"; DateFormat df = new SimpleDateFormat("HH:mm:ss"); Date time = df.parse(timeinsec); 
0
source

All Articles