Calculate date/time difference in java
try
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
NOTE: this assumes that diff
is non-negative.
How can I calculate a time difference in Java?
String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Difference is in milliseconds.
I modified sfaizs post.
Java - Time difference in minutes
This is not working because when you create a new date with just a time in it, it's assuming the day is "today".
What you could do is:
// This example works
String dateStart = "2045";
String dateStop = "2300";
// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
// MY ADDITION TO YOUR CODE STARTS HERE
if(d2.before(d1)){
Calendar c = Calendar.getInstance();
c.setTime(d2);
c.add(Calendar.DATE, 1);
d2 = c.getTime();
}
// ENDS HERE
long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");
But you should consider using Java 8 new Date/Time features, or Joda Time.
Java calculate time difference error
Date
is a type for a time instant(時刻), not a time interval(時間).
So, if you want to caculate the time difference(time inverval) between two time instants(Date objects), you will get the time difference in another type, such as long
(in seconds) or type in the external library.
Refer to http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
The first code does not use an external library, but you have to convert milliseconds into seconds, minutes, hours, and so on.
Here is the important part:
Date d1 = ...;
Date d2 = ...;
//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.");
The second code does use an external library, Joda-Time, which is one of the most famous Java library for Time.
Here is the important part:
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");
If you want to use Joda-Time library, you can also use another type for time invervals, Interval
: http://joda-time.sourceforge.net/key_interval.html
EDIT:
The
Date
class uses internal long variable to represent the time instant.And the long value is the time difference in milliseconds between some time instant,
namely January 1, 1970, 00:00:00 GMT
(which is specified in http://docs.oracle.com/javase/7/docs/api/java/util/Date.html),
which is January 1, 1970, 09:00:00
in Japan Standard Time because JST (UTC +09:00).
So, 23:00:05 - 08:00:01 will be 15:00:04, and will be converted into Japan Standard Time (UTC +09:00) = 24:00:04 (January 1, 1970), i.e 00:00:04 (January 2, 1970).
If you calculate 08:00:01 - 08:00:01, then it will be 1970-01-01 00:00:00 in UTC, which is 1970-01-01 09:00:00 in the Japan Standard time.
EDIT2: I made some mistake. I didn't use the Japan Standard Time when parsing. Anyway, the result is the same.
date1 = 08:00:01 in Japan = 23:00:01 in UTC
date2 = 23:00:05 in Japan = 14:00:05 in UTC
date = 14:00:05 in UTC - 23:00:01 in UTC = 15:00:04 in UTC
= 23:00:05 in Japan - 08:00:01 in Japan = 15:00:04 in UTC (NOT in JAPAN)
Why? Because the calculation is done with the long value I mentioned earlier which is calculated in GMT (UTC +00:00, or just UTC).
The long value is in UTC even if you specified you are using Japan time. Date
stores it converted to UTC, so it will get the time you gave -09:00
, and the internal process in Date
is done with UTC. If you want to print it, Date
just add +09:00
calculation.
You can also see it as:23:00:05 with (+09:00) - 08:00:01 with (+09:00) = 15:00:04 with (+00:00)
anyway, 15:00:04 UTC
is 00:00:04 JST
, so if you print it, you will see the Japan Time 00:00:04
since you specified you are using Japan Standard Time.
Difference between two DateTime objects in minutes
LocalDateTime fromdate = LocalDateTime.of(orderYear,orderMonth,orderDay,orderHour,orderMinute,orderSeconds);
LocalDateTime todate = LocalDateTime.of(deliverYear, deliverMonth, deliverDay,deliverHour,deliverMinute,deliverSeconds);
Duration difference = Duration.between(fromdate, todate);
Then you can format it using something similar to...
long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();
// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);
And just to prove the point...
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
List<LocalDateTime> from = new ArrayList<>(5);
List<LocalDateTime> to = new ArrayList<>(5);
from.add(LocalDateTime.parse("2018-06-16 02:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 03:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 04:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 05:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 06:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 02:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 03:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 04:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 05:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 06:00:00", formatter));
for (int index = 0; index < from.size(); index++) {
LocalDateTime fromDate = from.get(index);
LocalDateTime toDate = to.get(index);
String difference = formatDurationBetween(fromDate, toDate);
System.out.println(fromDate.format(formatter) + " - " + toDate.format(formatter) + " = " + difference);
}
}
public static String formatDurationBetween(LocalDateTime from, LocalDateTime to) {
Duration difference = Duration.between(from, to);
long days = difference.toDays();
difference = difference.minusDays(days);
long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();
return String.format("%dd %dh %02dm", days, hours, mins);
}
}
Outputs...
2018-06-16 02:00:00 - 2018-06-18 02:00:00 = 2d 0h 00m
2018-06-16 03:00:00 - 2018-06-18 03:00:00 = 2d 0h 00m
2018-06-16 04:00:00 - 2018-06-18 04:00:00 = 2d 0h 00m
2018-06-16 05:00:00 - 2018-06-18 05:00:00 = 2d 0h 00m
2018-06-16 06:00:00 - 2018-06-18 06:00:00 = 2d 0h 00m
You can of course make your own formatting algorithm based on your needs
How to find the duration of difference between two dates in java?
try the following
{
Date dt2 = new DateAndTime().getCurrentDateTime();
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
if (diffInDays > 1) {
System.err.println("Difference in number of days (2) : " + diffInDays);
return false;
} else if (diffHours > 24) {
System.err.println(">24");
return false;
} else if ((diffHours == 24) && (diffMinutes >= 1)) {
System.err.println("minutes");
return false;
}
return true;
}
Calculating Time and Date difference
You do not need variables for this, use directly the textFieldExpression
If the fields MO_DATECREATED
and MO_DATECOMPLETED
are declared:
as java.lang.Date
<field name="MO_DATECREATED" class="java.lang.Date">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
The textFieldExpression
would be ($F{MO_DATECOMPLETED}.getTime()-$F{MO_DATECREATED}.getTime())/(1000*60*60) + " hours"
.
Hey thats java exactly so to understand what it does check out this: How to calculate time difference in java?
as java.lang.String
<field name="MO_DATECREATED" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
We need to parse them to Date
object's first.. your pattern is mm/dd/yy hh:mm a
(new java.text.SimpleDateFormat("mm/dd/yy hh:mm a").parse($F{MO_DATECOMPLETED}).getTime()-new java.text.SimpleDateFormat("mm/dd/yy hh:mm a").parse($F{MO_DATECREATED}).getTime())/(1000*60*60) + " hours"
Considering that they maybe null
we better add a printWhenExpression
as well
Complete result
<textField>
<reportElement x="0" y="0" width="100" height="20" uuid="eac93a84-7901-4205-b09c-556d48dc05e1">
<printWhenExpression><![CDATA[new java.lang.Boolean($F{MO_DATECREATED}!=null && $F{MO_DATECOMPLETED}!=null)]]></printWhenExpression>
</reportElement>
<textFieldExpression><![CDATA[(new java.text.SimpleDateFormat("mm/dd/yy hh:mm a").parse($F{MO_DATECOMPLETED}).getTime()-new java.text.SimpleDateFormat("mm/dd/yy hh:mm a").parse($F{MO_DATECREATED}).getTime())/(1000*60*60) + " hours"]]></textFieldExpression>
</textField>
No doubt that it is better that they are java.lang.Date
object, both the report will fill faster, no risk for parsing error and you can export correctly to excel ecc. To format a java.lang.Date
object as you wish just use the pattern property.
EDIT: Users has opted for the java.util.Date
and asked how he can display also minutes, for this I have created a general question on How to create a single expression displaying time difference between two Date's as years, months, days, hours, minutes, seconds and it is now answered
This was the temporary solution
<textField>
<reportElement x="0" y="0" width="100" height="20" uuid="eac93a84-7901-4205-b09c-556d48dc05e1">
<printWhenExpression><![CDATA[new java.lang.Boolean($F{MO_DATECREATED}!=null && $F{MO_DATECOMPLETED}!=null)]]></printWhenExpression>
</reportElement>
<textFieldExpression><![CDATA[($F{MO_DATECOMPLETED}.getTime()-$F{MO_DATECREATED}.getTime()) / (24* 60 * 60 * 1000) + " days " +($F{MO_DATECOMPLETED}.getTime()-$F{MO_DATECREATED}.getTime()) / (60 * 60 * 1000) % 24 + " hours " + ($F{MO_DATECOMPLETED}.getTime()-$F{MO_DATECREATED}.getTime()) / (60 * 1000) % 60 + " minutes"]]></textFieldExpression>
</textField>
Calculating the difference between two Java date instances
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
EDIT: By the way, Joda has two concepts: Interval
for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration
that represents a length of time without the actual time boundaries (e.g. represent two hours!)
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()
Related Topics
How to Lock a File Using Java (If Possible)
How to Put a Control in the Jtableheader of a Jtable
How to Unescape a Java String Literal in Java
Java Arrays Printing Out Weird Numbers and Text
Java: Recommended Solution For Deep Cloning/Copying an Instance
Spring Boot Configure and Use Two Data Sources
Avoid Synchronized(This) in Java
Netbeans Gui Editor Generating Its Own Incomprehensible Code
Difference Between String Object and String Literal
Java Swing Revalidate() VS Repaint()
Java Hashmap: How to Get Key from Value
Difference Between Inheritance and Composition
How to Make a Deep Copy of an Object