Question

I have time in seconds i want to convert it into a format like 6w 3d 9h 5m . Can someone please provide a method which can do this task. Thanks :) w=weeks d=days h=hours m=minutes

I have tried the below code but i dont get weeks using

int day = (int)TimeUnit.SECONDS.toDays(seconds);        
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
System.out.println("Day :"+day+" Hours :"+hours+" Minutes :"+minute); 
Was it helpful?

Solution 2

int seconds=98765410;
int weeks = (int) (TimeUnit.SECONDS.toDays(seconds) / 7);
int days = (int) (TimeUnit.SECONDS.toDays(seconds) - 7 * weeks);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(days) - TimeUnit.DAYS.toHours(7*weeks);
long minutes = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
System.out.println(weeks+"w "+days+"d "+hours+"h "+minutes+"m");

Will print out:

163w 2d 2h 50m

OTHER TIPS

this will give you:

1w 4d 10h 20m

there should be more elegant way, but this works:

long s = 987654l;
        final long M=60,H=60*M, D=24*H, W=7*D; 
        long w = s/W;
        s%=W; 
        long d = s/D;
        s%=D; 
        long h = s/H;
        s%=H; 
        long m = s/M;

        System.out.printf("%dw %dd %dh %dm",w,d,h,m);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top