java - Formatting miliseconds to hh:mm:ss format -


i having miliseconds value , want display time subtracting 5 minutes current miliseconds value in hh:mm:ss format.

code

string str = string.format("%02d:%02d:%02d",                                  timeunit.milliseconds.tohours((cal.gettimeinmillis()-300000)),                                 timeunit.milliseconds.tominutes(cal.gettimeinmillis()-300000) -                                  timeunit.hours.tominutes(timeunit.milliseconds.tohours(cal.gettimeinmillis()-300000)),                                 timeunit.milliseconds.toseconds(cal.gettimeinmillis()-300000) -                                  timeunit.minutes.toseconds(timeunit.milliseconds.tominutes(cal.gettimeinmillis()-300000)));  toast.maketext(getapplicationcontext(), "alarm set."+str, toast.length_long).show() 

output now

alarm set. 386467:25:00

output required

alarm set. 07:25:00

as see minutes , seconds getting retrieved quiet right there's problem hours.

p.s

1.i referred this post.they works fine.but don't know why not in case.

2.i sure want hours value i.e 07 have set value using calendar.hour , getting displayed if use cal.get(calendar.hour).cal of course object of calendar class.

alternative solution

 simpledateformat sdf = new simpledateformat("hh:mm:ss");  string str1 = sdf.format(new date(cal.gettimeinmillis()-300000));  toast.maketext(getapplicationcontext(), "alarm set."+str1, toast.length_long).show(); 

it working fine is, reason see such huge offset because calculating total number of hours since unix epoch.

when calendar.getinstance() gets current point in time. converting milliseconds total millis since unix epoch.

you can check total number of hours since epoch:

//check hours since unix epoch system.out.println(system.currenttimemillis() / 3600000); 

output:

386439 

you code below produce result appended minutes , seconds of current point in time:

calendar cal = calendar.getinstance();  string str = string         .format("%02d:%02d:%02d",                 timeunit.milliseconds.tohours((cal.gettimeinmillis() - 300000)),                 timeunit.milliseconds.tominutes(cal.gettimeinmillis() - 300000)                         - timeunit.hours.tominutes(timeunit.milliseconds                                 .tohours(cal.gettimeinmillis() - 300000)),                 timeunit.milliseconds.toseconds(cal.gettimeinmillis() - 300000)                         - timeunit.minutes.toseconds(timeunit.milliseconds                                 .tominutes(cal.gettimeinmillis() - 300000)));  system.out.println(str); 

output:

386439:38:20 

note: reference example considers constant value of millis (3600000) hence gets readable time there.

the better solution provided in other answer provides requirement.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -