如何使用Java计算时间跨度并格式化输出?

我想花两次(从纪元以来的秒数),以如下格式显示两者之间的差异:


2分钟

1小时15分钟

3小时9分钟

1分钟前

1小时2分钟前

我该怎么做?


犯罪嫌疑人X
浏览 681回答 5
5回答

慕田峪9158850

Date start = new Date(1167627600000L); // JANUARY_1_2007    Date end = new Date(1175400000000L); // APRIL_1_2007    long diffInSeconds = (end.getTime() - start.getTime()) / 1000;    long diff[] = new long[] { 0, 0, 0, 0 };    /* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);    /* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;    /* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;    /* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));    System.out.println(String.format(        "%d day%s, %d hour%s, %d minute%s, %d second%s ago",        diff[0],        diff[0] > 1 ? "s" : "",        diff[1],        diff[1] > 1 ? "s" : "",        diff[2],        diff[2] > 1 ? "s" : "",        diff[3],        diff[3] > 1 ? "s" : ""));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java