Domanda

I have the following code below, I'm trying to compare two dates using Joda, so I can get the difference in hours. This works fine for two dates on the same day (see test 1 below). However, if I'm comparing two dates that are not on the same day it just gives the wrong result (see test 2 below)

DateTime end = new DateTime(event.endTime)
DateTime start = new DateTime(event.startTime)

Period p = new Period(start, end);

long hours = p.getHours();
long minutes = p.getMinutes();

System.out.println("Task title :"+ event.getTitle()+ " ...The differnce in hours is : "+hours+"  The differnce in minutes is : "+minutes)

Printed Results from two tests.

The first being a task that's on the same day, with 3 hours difference.

The second being a task that ends the day after ... which doesn't give the difference properly like the previous task test

This is the END TIME :2012-10-12 14:15:00.0... This is the START TIME :2012-10-12 10:30:00.0
Task title :Test 1 ...The differnce in hours is : 3  The differnce in minutes is : 45

This is the END TIME :2012-10-12 22:00:00.0... This is the START TIME :2012-10-11 22:00:00.0
Task title :Test 999 ...The differnce in hours is : 0  The differnce in minutes is : 0

Any assistance is appreciated

È stato utile?

Soluzione

Never used Jodatime before, and haven't tested this, but I did find a couple things:

First, a Jodatime Period has a method toStandardHours(), which is probably what you want, instead of .getHours(). Whereas .getHours() returns 0 for your 2nd test, because .getDays() would return 1, .toStandardHours() should return 24. http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html

Also, you could use the Hours function "hoursBetween":

 static Hours   hoursBetween(ReadableInstant start, ReadableInstant end)

Check the API: http://joda-time.sourceforge.net/apidocs/org/joda/time/Hours.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top