Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a negative milliseconds into correct timeZone in Java

I am working with Java dates , I am unable to get out of this issue. In my file the Time value is saved like (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 is when I assigned the value and time variables. time.fastTime variable show "-17992000"

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

Anybody can help to fix TimeZone issue. My current time zone is GMT+5

like image 517
DareDevil Avatar asked Mar 22 '23 07:03

DareDevil


2 Answers

Try this;

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);
like image 198
newuser Avatar answered Mar 24 '23 21:03

newuser


here is the convert back 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: the value of hms = -4:-59:-51

like image 36
DareDevil Avatar answered Mar 24 '23 19:03

DareDevil