在JAVA中将秒转换为W,D,H,M格式

时间:2013-01-24 09:28:14

标签: java seconds time-format

我有时间在几秒钟内我想将其转换为6w 3d 9h 5m的格式。有人可以提供一种方法来完成这项任务。谢谢 :) W =周 d =天 h =小时 m =分钟

我已经尝试了以下代码,但我没有使用

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); 

2 个答案:

答案 0 :(得分:3)

这会给你:

1w 4d 10h 20m

应该有更优雅的方式,但这有效:

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);

答案 1 :(得分: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");

将打印出来:

163w 2d 2h 50m