如何比较两个日历对象?

时间:2014-08-17 13:34:30

标签: java datetime time calendar

我想比较两个日期对象:

    String format = "MM/dd/yyyy hh:mm a";
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    fakeDate = sdf.parse("15/07/2013 11:00 AM");
    fakeDate2 = sdf.parse("15/07/2013 12:00 AM");

int diff = date2.getHours() - date1.getHours();

然后我看到不推荐使用getHours。

所以我用过:

    Calendar calendar1 = Calendar.getInstance();
    calendar.setTime(new Date("15/7/2013 11:00AM"));
    Calendar calendar2 = Calendar.getInstance();
    calendar.setTime(new Date("11/7/2013 12:00AM"));

calendar1.get(Calendar.HOUR_OF_DAY) - calendar2.get(Calendar.HOUR_OF_DAY)

然后我看到差异为零。我想我会一直更改相同的日历实例并将其与自身进行比较。没有?

你怎么写这个?

2 个答案:

答案 0 :(得分:0)

new Date("15/7/2013 11:00AM")

不是构造Date对象的正确方法。它也已弃用。在第一个示例中使用正确的SimpleDateFormat

格式MM/dd/yyyy hh:mm a根据输入日期字符串不正确。

应该是这样的。

String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Date fakeDate2 = sdf.parse("15/07/2013 12:00 AM");

Calendar cal = Calendar.getInstance();

cal.setTime(fakeDate); //set time to first date
int hours1 = cal.get(Calendar.HOUR); // get the hours

cal.setTime(fakeDate2); // set time to second date
int hours2 = cal.get(Calendar.HOUR); // get the hours

System.out.println(hours1 - hours2); // 11 hours

答案 1 :(得分:0)

你似乎真的很困惑,虽然这是折旧的,这段代码会给你11小时的差异,这是有道理的

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
    Date fakeDate = dateFormat.parse("15/07/2013 11:00 AM");
    Date fakeDate2 = dateFormat.parse("15/07/2013 12:00 AM");
    System.out.println(fakeDate.getHours()-fakeDate2.getHours());

或者,如果您对使用Calendar感兴趣,可以这样做

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(fakeDate);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(fakeDate2);
    System.out.println(calendar.get(Calendar.HOUR_OF_DAY) - 
                                 calendar2.get(Calendar.HOUR_OF_DAY));

您将获得相同的11小时差异或只是这样做

long millisForNewDate = toDate.getTime();
long millisForOldDate = fromDate.getTime();
long difference = millisForNewDate - millisForOldDate;
int hoursDifferenceBetweenDates = (int)(difference/(1000*60*60));