1

我需要将时间差计算为季度、周、天、小时和秒。我无法得到正确的公式。以下公式应返回:3 个季度、12 周、6 天、23 小时和 59 分钟。我绝不是数学奇才,所以任何帮助都会很棒。

long difference = 31535872360L;/*A few seconds short of a year*/

long min =   (int) ((difference / (1000*60))%60);/*Returns 59 Minutes*/
long hours = (int) ((difference / (1000*60*60)) % 24);/*Returns 23 Hours*/
long days =  (int) ((difference / (1000*60*60*24)) % 7);/*Returns 0 Days*/
long weeks = (int) ( difference / (1000*60*60*24*7)% 12);/*Returns 4 Weeks*/
long quarters = (int) (((difference / (1000*60*60*24*7)%12)/3)+1);/*Returns 2 Quarters*/
4

2 回答 2

0

我相信这种方式更干净,更不容易出错:

private static final long MIN_MS = 1000 * 60;
private static final long HOUR_MS = MIN_MS * 60;
private static final long DAY_MS = HOUR_MS * 24;
private static final long WEEK_MS = DAY_MS * 7;
private static final long QUARTER_MS = WEEK_MS * 12;

public static void main(String[] args) throws Exception {
    long msecs = 31535872360L;/*A few seconds short of a year*/
    long q = msecs / QUARTER_MS;
    msecs -= q * QUARTER_MS;
    long w = msecs / WEEK_MS;
    msecs -= w * WEEK_MS;
    long d = msecs / DAY_MS;
    msecs -= d * DAY_MS;
    long h = msecs / HOUR_MS;
    msecs -= h * HOUR_MS;
    long min = msecs / MIN_MS;
    msecs -= min * MIN_MS;
    long secs = msecs / 1000;
    System.out.printf("%d q,%d w, %d d, %d:%d:%d \n", q, w, d, h, min, secs);
}
于 2013-02-05T22:50:13.467 回答
0

我认为你的季度公式应该是

long quarters = (int) ((difference / (1000*60*60*24*7*12) % 4);
于 2013-02-05T18:59:55.913 回答