簡體   English   中英

如何獲得從現在到未來時間的月,周,日和小時數?

[英]How to get number of months, weeks, days and hours from now to a future time?

我需要找出使用Java從現在到未來時間剩余的月,周,日和小時數。 我不能使用像Joda這樣的任何第三方庫。 我怎么能只使用JDK類呢?

到目前為止,這是我想出的。 除了某些情況外,它有點有用:

public class DateUtil {

public static Integer[] components(Date from, Date to) {
    Integer[] result = new Integer[4];
    //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    //df.setTimeZone(TimeZone.getTimeZone("EST"));

    Calendar fromCal = new GregorianCalendar();
    Calendar toCal = new GregorianCalendar();

    fromCal.setTime(from);
    toCal.setTime(to);

    int months = 0;
    do {
        fromCal.add(Calendar.MONTH, 1);
        ++months;
        //System.out.println(df.format(fromCal.getTime()));
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.MONTH, -1);
    --months;

    int days = 0;
    do {
        fromCal.add(Calendar.DAY_OF_YEAR, 1);
        ++days;
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.DAY_OF_YEAR, -1);
    --days;

    int hours = 0;
    do {
        fromCal.add(Calendar.HOUR_OF_DAY, 1);
        ++hours;
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.HOUR_OF_DAY, -1);
    --hours;

    int minutes = 0;
    do {
        fromCal.add(Calendar.MINUTE, 1);
        ++minutes;
    } while (fromCal.before(toCal));

    result[0] = months;
    result[1] = days;
    result[2] = hours;
    result[3] = minutes;

    return result;
}

public static void main(String[] args) {
    try {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        df.setTimeZone(TimeZone.getTimeZone("EST"));

        Date from = df.parse("2014-03-29 00:00");
        Date to = df.parse("2014-05-29 00:00");
        Integer result[] = components(from, to);

        System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n", 
                result[0], result[1], result[2], result[3]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

如果您有2月中間且開始日期是月末,則會產生不可接受的結果。 例如:

來自:2013年12月31日至:2014年12月31日

差異將產生:12個月,3天。

為什么不使用Java類DateCalendar

這些類已經內置了功能,可以幫助您計算兩個日期之間的差異。 大多數Date方法似乎都被棄用了,所以我建議使用Calendar。 祝好運!

我的一位同事最終得出了正確的答案。 逐步向日歷添加月份的問題是您從1月31日到2月28日到3月28日,而不是3月31日。這會增加不准確性。 解決方案是在原始開始日期添加1個月,2個月,3個月等。 然后你從1月31日到2月28日到3月31日。無論如何,這是他的解決方案,我稍微改變了。

public class TimeSpan {
    public int months;
    public int days;
    public int hours;
    public int minutes;
}

class DateCalculator {
    public static TimeSpan difference(Date later, Date earlier) {
        TimeSpan v = new TimeSpan();

        /* Add months until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.months++;
        }
        v.months--;

        /* Add days until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.days++;
        }
        v.days--;

        /* Add hours until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.hours++;
        }
        v.hours--;
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.minutes++;
        }
        v.minutes--;

        return v;
    }

    private static Date calculateOffset(Date start, TimeSpan offset) {
        Calendar c = new GregorianCalendar();

        c.setTime(start);

        c.add(Calendar.MONTH, offset.months);
        c.add(Calendar.DAY_OF_YEAR, offset.days);
        c.add(Calendar.HOUR, offset.hours);
        c.add(Calendar.MINUTE, offset.minutes);

        return c.getTime();
    }
     public static void main(String[] args) {
            try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    df.setTimeZone(TimeZone.getTimeZone("EST"));

                    Date from = df.parse("2013-01-31 00:00");
                    Date to = df.parse("2014-01-31 10:20");
                    TimeSpan ts = difference(to, from);

                    System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n",
                                    ts.months, ts.days, ts.hours, ts.minutes);
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM