如何在不使用api的情况下获得两个日期差异?

时间:2014-01-07 06:31:32

标签: java date

我试图通过以下方式,但我的导游指示我不使用api ..  任何人都可以给它解决方案吗?

public class DateDifferenceExample{

    public static void main(String[] args){

    //get instance of Calendar objects
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();

    //set two dates we want to know difference of
    cal1.set(2006, 12, 30);
    cal2.set(2007, 5, 3);

    long milis1 = cal1.getTimeInMillis();  
    long milis2 = cal2.getTimeInMillis();

    //difference in milliseconds
    long diff = milis2 - milis1;

    //difference in seconds
    long diffSeconds = diff / 1000;

    //difference in minutes
    long diffMinutes = diff / (60 * 1000);

    //difference in hours
    long diffHours = diff / (60 * 60 * 1000);

    //difference in days
    long diffDays = diff / (24 * 60 * 60 * 1000);

    System.out.println("Date difference in milliseconds: " + diff + " milliseconds.");     
    System.out.println("Date difference in seconds: " + diffSeconds + " seconds.");
    System.out.println("Date difference in minutes: " + diffMinutes + " minutes.");
    System.out.println("Date difference in hours: " + diffHours + " hours.");      
    System.out.println("Date difference in days: " + diffDays + " days.");

    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用compareTo()方法或before()after()方法来比较日期。如果您需要“差异”,那么我建议您开始与年份,月份和日期进行比较。这样你就可以得到两个日期之间的确切差异。

  

我不想使用任何方法

需要使用方法来获取年,月和日。看看:Calendar.get()

示例:

Date1: 01 / 01 / 2014
Date2: 02 / 12 / 2015 

 Start with year. Subtract the years, use Math.abs() to get the absolute value.
 Then go for month. Subtract the months, use Math.abs() to get the absolute value.
 Then finally the day. Same story.

 The two dates are 1 year, 11 month and 1 day apart  

注意:日期为dd / mm / yyyy格式

答案 1 :(得分:0)

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.set(2006, 12, 30);
        cal2.set(2007, 5, 3);
        long startTime = cal1.getTimeInMillis();
        long endTime = cal2.getTimeInMillis();          

        long diff = endTime - startTime;
        long hoursRem=diff%(1000*60*60);
        diff=diff-hoursRem;
        long hours=diff/(1000*60*60);
        diff=diff+hoursRem;
        diff = diff - (hours * 60 * 60 * 1000);
        long minRem=diff%(1000*60);
        diff=diff-minRem;
        long min=diff/(1000*60);
        diff=diff+minRem;
        diff = diff - (min * 60 * 1000);
        long seconds=diff/1000;
        System.out.println("hh = "+hours +"  min ="+min+" sec= "+seconds);

答案 2 :(得分:0)

代码没问题。但它可能并不精确,因为它不需要夏令时。

考虑一下

    GregorianCalendar c1 = new GregorianCalendar(2014, 2, 29, 4, 0, 0);
    GregorianCalendar c2 = new GregorianCalendar(2014, 2, 30, 4, 0, 0);

天数的差异是1整天。但是这个

    System.out.println(c2.getTimeInMillis() - c1.getTimeInMillis());

打印

82800000

毫秒差异小于1小时,diffDays代码将产生0