将持续时间转换为季度

时间:2013-02-05 18:53:48

标签: java android datetime

我需要计算季度,周,天,小时和秒的时差。我无法使公式正确。下面的公式应该返回: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*/

2 个答案:

答案 0 :(得分:0)

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

long quarters = (int) ((difference / (1000*60*60*24*7*12) % 4);

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