Java Joda time查找小时之间的差异

Java Joda time查找小时之间的差异,java,android,datetime,jodatime,Java,Android,Datetime,Jodatime,我有一个日期字符串: Thu, 15 Jan 2015, 9:56 AM 我将其转换为日期变量: Thu Jan 15 09:56:00 GMT+05:30 2015 使用: String pattern = "EEE, d MMM yyyy, hh:mm a"; try { date = new SimpleDateFormat(pattern).parse(getPref("refresh", getApplicationContext()));

我有一个日期字符串:

Thu, 15 Jan 2015, 9:56 AM
我将其转换为日期变量:

Thu Jan 15 09:56:00 GMT+05:30 2015
使用:

String pattern = "EEE, d MMM yyyy, hh:mm a";
        try {
            date = new SimpleDateFormat(pattern).parse(getPref("refresh", getApplicationContext()));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
现在,我有了以下函数,并将日期变量传递给以下函数:

public static int getDiffHour(Date first) {
        int hoursBetween = Hours.hoursBetween(new LocalDate(first), new LocalDate()).getHours();
        return hoursBetween;
    }
它总是返回0。可能的原因是什么

请尝试以下代码:-

public static void main(String[] args) {

    String dateStart = "01/14/2012 09:29:58";
    String dateStop = "01/15/2012 10:31:48";

    //HH converts hour in 24 hours format (0-23), day calculation
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateStop);

        //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.print(diffDays + " days, ");
        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");
        System.out.print(diffSeconds + " seconds.");

    } catch (Exception e) {
        e.printStackTrace();
    }

}
有关更多信息,请参阅以下链接:-

像这样试试

int diff_hrs = getDiffHours(date,new Date());// pass your date object as startDate and pass current date as your endDate


public int getDiffHours(Date startDate, Date endDate){

  Interval interval = new Interval(startDate.getTime(), endDate.getTime());
  Period period = interval.toPeriod();
  return period.getHours();
}

请检查此链接如果endDate是currentdate怎么办?它不允许我执行新的LocalDate().getTime。您可能会遇到问题,因为解析日期时使用了不同的格式,而不是
JodaTime的
LocalDate
所使用的格式。所以我会坚持让你按照我的回答来解析它。就像一个符咒一样:)谢谢你,伙计!
int diff_hrs = getDiffHours(date,new Date());// pass your date object as startDate and pass current date as your endDate


public int getDiffHours(Date startDate, Date endDate){

  Interval interval = new Interval(startDate.getTime(), endDate.getTime());
  Period period = interval.toPeriod();
  return period.getHours();
}