How to subtract two system times using Java [duplicate] - java

This question already has answers here:
How to convert milliseconds to "hh:mm:ss" format?
(19 answers)
How do I measure time elapsed in Java? [duplicate]
(15 answers)
How to convert Milliseconds to "X mins, x seconds" in Java?
(29 answers)
Closed 3 years ago.
I have written a Selenium script and I want to calculate the total execution time of the script. How do I subtract the time returned by system when the script started executing and when it’s ended?
I'm using Date and SimpleDateFormat class of Java to get the system time and then format it but the method seems wrong that I'm following to return total time.
String dateStart = "01/14/2012 23:05:49";
String dateStop = "01/15/2012 23:07:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(dateStart);
d2 = sdf.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();
}

Use below code:-
TimeUnit Enum
The following expression uses the TimeUnit enum (Java 5 and later) to convert from nanoseconds to seconds:
public static void main (String[] args) {
long start = System.nanoTime();
//some try with nested loops
long end = System.nanoTime();
long elapsedTime = end - start;
System.out.println("elapsed: " + elapsedTime + "nano seconds\n");
//convert to seconds
TimeUnit seconds = new TimeUnit();
System.out.println("which is " + TimeUnit.NANOSECONDS.toSeconds(elapsedTime) + " seconds");
}}

Related

Get difference in minutes between two dates java [duplicate]

This question already has answers here:
How to convert Milliseconds to "X mins, x seconds" in Java?
(29 answers)
Closed 6 years ago.
I want to calculate difference between 2 dates in hours/minutes/seconds.
I have a slight problem with my code here it is :
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
This should produce :
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
However I get this result :
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Can anyone see what I'm doing wrong here ?
I would prefer to use suggested java.util.concurrent.TimeUnit class.
long diff = d2.getTime() - d1.getTime();//as given
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
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.
If you are able to use external libraries I would recommend you to use Joda-Time, noting that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Example for between calculation:
Seconds.between(startDate, endDate);
Days.between(startDate, endDate);
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.
By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.
Here is a suggestion, using TimeUnit, to obtain each time part and format them.
private static String formatDuration(long duration) {
long hours = TimeUnit.MILLISECONDS.toHours(duration);
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;
long milliseconds = duration % 1000;
return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
Date startTime = sdf.parse("01:00:22,427");
Date now = sdf.parse("02:06:38,355");
long duration = now.getTime() - startTime.getTime();
System.out.println(formatDuration(duration));
The result is: 01:06:15,928
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
divide by 1000 to get the number of seconds -> rest is milliseconds
divide that by 60 to get number of minutes -> rest are seconds
divide that by 60 to get number of hours -> rest are minutes
or in java:
int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;
I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit class, but there were no answers using this in the way OP wanted it.
So here's another solution, should someone come by missing it ;-)
public class DateTesting {
public static void main(String[] args) {
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);
System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
}
}
Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit is a highly overlooked class.
Create a Date object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
difference-between-two-dates-in-java
Extracted the code from the link
public class TimeDiff {
/**
* (For testing purposes)
*
*/
public static void main(String[] args) {
Date d1 = new Date();
try { Thread.sleep(750); } catch(InterruptedException e) { /* ignore */ }
Date d0 = new Date(System.currentTimeMillis() - (1000*60*60*24*3)); // About 3 days ago
long[] diff = TimeDiff.getTimeDifference(d0, d1);
System.out.printf("Time difference is %d day(s), %d hour(s), %d minute(s), %d second(s) and %d millisecond(s)\n",
diff[0], diff[1], diff[2], diff[3], diff[4]);
System.out.printf("Just the number of days = %d\n",
TimeDiff.getTimeDifference(d0, d1, TimeDiff.TimeField.DAY));
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #param field The field we're interested in out of
* day, hour, minute, second, millisecond
*
* #return The value of the required field
*/
public static long getTimeDifference(Date d1, Date d2, TimeField field) {
return TimeDiff.getTimeDifference(d1, d2)[field.ordinal()];
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #return The fields day, hour, minute, second and millisecond
*/
public static long[] getTimeDifference(Date d1, Date d2) {
long[] result = new long[5];
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(d1);
long t1 = cal.getTimeInMillis();
cal.setTime(d2);
long diff = Math.abs(cal.getTimeInMillis() - t1);
final int ONE_DAY = 1000 * 60 * 60 * 24;
final int ONE_HOUR = ONE_DAY / 24;
final int ONE_MINUTE = ONE_HOUR / 60;
final int ONE_SECOND = ONE_MINUTE / 60;
long d = diff / ONE_DAY;
diff %= ONE_DAY;
long h = diff / ONE_HOUR;
diff %= ONE_HOUR;
long m = diff / ONE_MINUTE;
diff %= ONE_MINUTE;
long s = diff / ONE_SECOND;
long ms = diff % ONE_SECOND;
result[0] = d;
result[1] = h;
result[2] = m;
result[3] = s;
result[4] = ms;
return result;
}
public static void printDiffs(long[] diffs) {
System.out.printf("Days: %3d\n", diffs[0]);
System.out.printf("Hours: %3d\n", diffs[1]);
System.out.printf("Minutes: %3d\n", diffs[2]);
System.out.printf("Seconds: %3d\n", diffs[3]);
System.out.printf("Milliseconds: %3d\n", diffs[4]);
}
public static enum TimeField {DAY,
HOUR,
MINUTE,
SECOND,
MILLISECOND;
}
}
// d1, d2 are dates
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.");
Joda-Time
Joda-Time 2.3 library offers already-debugged code for this chore.
Joad-Time includes three classes to represent a span of time: Period, Interval, and Duration. Period tracks a span as a number of months, days, hours, etc. (not tied to the timeline).
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yy/MM/dd HH:mm:ss" ).withZone( timeZone );
DateTime dateTimeStart = formatter.parseDateTime( "11/03/14 09:29:58" );
DateTime dateTimeStop = formatter.parseDateTime( "11/03/14 09:33:43" );
Period period = new Period( dateTimeStart, dateTimeStop );
PeriodFormatter periodFormatter = PeriodFormat.getDefault();
String output = periodFormatter.print( period );
System.out.println( "output: " + output );
When run…
output: 3 minutes and 45 seconds
Here is my code.
import java.util.Date;
// to calculate difference between two days
public class DateDifference {
// to calculate difference between two dates in milliseconds
public long getDateDiffInMsec(Date da, Date db) {
long diffMSec = 0;
diffMSec = db.getTime() - da.getTime();
return diffMSec;
}
// to convert Milliseconds into DD HH:MM:SS format.
public String getDateFromMsec(long diffMSec) {
int left = 0;
int ss = 0;
int mm = 0;
int hh = 0;
int dd = 0;
left = (int) (diffMSec / 1000);
ss = left % 60;
left = (int) left / 60;
if (left > 0) {
mm = left % 60;
left = (int) left / 60;
if (left > 0) {
hh = left % 24;
left = (int) left / 24;
if (left > 0) {
dd = left;
}
}
}
String diff = Integer.toString(dd) + " " + Integer.toString(hh) + ":"
+ Integer.toString(mm) + ":" + Integer.toString(ss);
return diff;
}
}
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
Well, I'll try yet another code sample:
/**
* Calculates the number of FULL days between to dates
* #param startDate must be before endDate
* #param endDate must be after startDate
* #return number of day between startDate and endDate
*/
public static int daysBetween(Calendar startDate, Calendar endDate) {
long start = startDate.getTimeInMillis();
long end = endDate.getTimeInMillis();
// It's only approximation due to several bugs (#see java.util.Date) and different precision in Calendar chosen
// by user (ex. day is time-quantum).
int presumedDays = (int) TimeUnit.MILLISECONDS.toDays(end - start);
startDate.add(Calendar.DAY_OF_MONTH, presumedDays);
// if we still didn't reach endDate try it with the step of one day
if (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
++presumedDays;
}
// if we crossed endDate then we must go back, because the boundary day haven't completed yet
if (startDate.after(endDate)) {
--presumedDays;
}
return presumedDays;
}
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);
You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter
Output:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)
As said before - think this is a good answer
/**
* #param d2 the later date
* #param d1 the earlier date
* #param timeUnit - Example Calendar.HOUR_OF_DAY
* #return
*/
public static int getTimeDifference(Date d2,Date d1, int timeUnit) {
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
if(timeUnit==Calendar.HOUR_OF_DAY)
return hours;
if(timeUnit==Calendar.MINUTE)
return minutes;
return seconds;
}

Java - Adding a 0 in the minutes of the current time (GMT) [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 6 years ago.
when I output the following code (taken from dr. Liang Introduction to Java, 10th ed., chapter 03 - selections)
/*
(Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays
the current time in GMT. Revise the program so that it prompts the user to enter
the time zone offset to GMT and displays the time in the specified time zone.
*/
import java.util.Scanner;
public class Ex_03_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone (GMT): ");
int gmt = input.nextInt();
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
currentHour = currentHour + gmt;
System.out.println("The current time is " + currentHour + ":"
+ currentMinute + ":" + currentSecond);
input.close();
}
}
the output is
Enter the time zone (GMT): 1
The current time is 11:2:31
How can I let display instead 11:02:31?
Thank you.
You can do something like this,
String currentMinuteStr=""+currentMinute ;
if(currentMinuteStr.length()==1){
currentMinuteStr="0"+currentMinuteStr;
}
I have just converted the minutes variable to string and then checked whether the length of the string is 1 that is whether it is a one digit minute and then i have appended the existing minutes to 0 and then you can display it as before like this,
System.out.println("The current time is " + currentHour + ":"
+ currentMinuteStr+ ":" + currentSecond);
You can format your input in C style printf using format method.
class NumericFormat
{
public static void main(String[] args) {
System.out.format("%02d%n",3);
//you can use \n too but %n is preferrable for format method
}
}
Get a better understanding at Java Docs
If link fails, here are some of the formatters.
On a side Note, to format and use Date and Time, Java 8 has clean inbuilt API. Get a look at this Oracle tutorial - Date Time Parsing and Formatting
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
currentHour = currentHour + gmt;
String strTime = "" + (currentHour < 10 ? "0" + currentHour : currentHour) +
(currentMinute < 10 ? "0" + currentMinute : currentMinute) +
(currentSecond < 10 ? "0" + currentSecond : currentSecond);
System.out.println("The current time is : " + strTime);

How to get time difference in java

I need to get time difference in my program.
ex: if user inserts earlier time as 08:30 and later time as 5:00 I need to calculate the time gap as 8 hours and 30 minutes(I want it to display as 08 hours 30 min)
I'm using phpmyadmin and my db has employee table,and in it there are three columns as earlierTime,laterTime and noOfHoursWorked and all these columns' data types are varchar(50) so i did this but output is not correct
public String timeDifference(String earlierTime, String laterTime) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(startTime);
Date date2 = format.parse(leavedTime);
long difference = date2.getTime() - date1.getTime();
String d = String.valueOf(difference);
return d;
}
can anyone please tell me what is wrong here I'm struggling with this problem for hours now
Is it okay if i change earlierTime, laterTime as date and noOfHoursWorked as int then i know in my output i can't get "8 hours 30 minutes" as output,so that I'd like to see it as "08:30"
java.time
In Java 8 and later use the java.time package. (Tutorial)
// Some exemplary dates
Calendar cal = Calendar.getInstance();
cal.set(2015, 9, 9, 10, 15, 0);
Date date1 = cal.getTime();
cal.set(2015, 9, 9, 14, 0, 20);
Date date2 = cal.getTime();
Duration duration = Duration.between(date1.toInstant(), date2.toInstant());
System.out.println(duration.toMinutes());
long minutes = duration.toMinutes()%60;
long hours = duration.toMinutes() / 60;
System.out.println("Duration " + hours + ":" + minutes);
long minutes = duration.toMinutes()%60;
long hours = duration.toMinutes() / 60; // this takes the math floor be default
System.out.println("Duration " + hours + ":" + minutes);
Joda-Time
In older Java, if only you can easily add external libraries, use Joda-Time. It's the best solution, since many peoples' workarounds do not take leap years into account while calculating date differences.
take a look at this :
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
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();
}
}
}

How to update time every second in Java emulator? [duplicate]

This question already has answers here:
Update time every second
(3 answers)
Closed 8 years ago.
I have been working on a code for an app but I cannot get the time to update in the emulator when I run the code. The code works in the compiler but not the emulator.
Any helpful suggestions would be greatly appreciated. The timer is a countdown to Christmas day.
Here is my code:
Calendar today = Calendar.getInstance();
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH, 25);
thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
thatDay.set(Calendar.HOUR, 0);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.AM_PM, 0);
System.out.println(thatDay.getTime());
ScheduledExecutorService scheduledExecutorService=
Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new ReadThisPeriod(thatDay), 0, 1,
TimeUnit.SECONDS);
long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
long days = diff / (60 * 60 * 24);
long hours = diff / (60 * 60) % 24;
long minutes = diff / 60 % 60;
long seconds = diff % 60;
TextView daysBox = (TextView) findViewById(R.id.s1Days);
daysBox.setText(" + "" + days + "" + hours + "" + minutes + " " + seconds + " ");
Keeping things very simple, I'd remove all Executors stuff and do something like:
TextView daysBox = (TextView) findViewById(R.id.s1Days);
// We create a runnable that will re-call itself each second to update time
Runnable printDaysToXmas=new Runnable() {
#Override
public void run() {
Calendar today = Calendar.getInstance();
long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
long days = diff / (60 * 60 * 24);
long hours = diff / (60 * 60) % 24;
long minutes = diff / 60 % 60;
long seconds = diff % 60;
daysBox.setText(" + "" + days + "" + hours + "" + minutes + " " + seconds + " ");
// we call this runnable again in 1000ms (1 sec)
daysBox.postDelayed(printDaysToXmas, 1000); // all views have a Handler you can use ;P
}
};
... and to start the process just do
printDaysToXmas.run();
... and to stop it, you can do
daysBox.removeCallbacks(printDaysToXmas);
Also some little add to rupps answer. You can use
DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution);
to simplify math and give more user readable string for user.

Calculate date/time difference in java [duplicate]

This question already has answers here:
How to convert Milliseconds to "X mins, x seconds" in Java?
(29 answers)
Closed 6 years ago.
I want to calculate difference between 2 dates in hours/minutes/seconds.
I have a slight problem with my code here it is :
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
This should produce :
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
However I get this result :
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Can anyone see what I'm doing wrong here ?
I would prefer to use suggested java.util.concurrent.TimeUnit class.
long diff = d2.getTime() - d1.getTime();//as given
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
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.
If you are able to use external libraries I would recommend you to use Joda-Time, noting that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Example for between calculation:
Seconds.between(startDate, endDate);
Days.between(startDate, endDate);
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.
By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.
Here is a suggestion, using TimeUnit, to obtain each time part and format them.
private static String formatDuration(long duration) {
long hours = TimeUnit.MILLISECONDS.toHours(duration);
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;
long milliseconds = duration % 1000;
return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
Date startTime = sdf.parse("01:00:22,427");
Date now = sdf.parse("02:06:38,355");
long duration = now.getTime() - startTime.getTime();
System.out.println(formatDuration(duration));
The result is: 01:06:15,928
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
divide by 1000 to get the number of seconds -> rest is milliseconds
divide that by 60 to get number of minutes -> rest are seconds
divide that by 60 to get number of hours -> rest are minutes
or in java:
int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;
I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit class, but there were no answers using this in the way OP wanted it.
So here's another solution, should someone come by missing it ;-)
public class DateTesting {
public static void main(String[] args) {
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);
System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
}
}
Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit is a highly overlooked class.
Create a Date object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
difference-between-two-dates-in-java
Extracted the code from the link
public class TimeDiff {
/**
* (For testing purposes)
*
*/
public static void main(String[] args) {
Date d1 = new Date();
try { Thread.sleep(750); } catch(InterruptedException e) { /* ignore */ }
Date d0 = new Date(System.currentTimeMillis() - (1000*60*60*24*3)); // About 3 days ago
long[] diff = TimeDiff.getTimeDifference(d0, d1);
System.out.printf("Time difference is %d day(s), %d hour(s), %d minute(s), %d second(s) and %d millisecond(s)\n",
diff[0], diff[1], diff[2], diff[3], diff[4]);
System.out.printf("Just the number of days = %d\n",
TimeDiff.getTimeDifference(d0, d1, TimeDiff.TimeField.DAY));
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #param field The field we're interested in out of
* day, hour, minute, second, millisecond
*
* #return The value of the required field
*/
public static long getTimeDifference(Date d1, Date d2, TimeField field) {
return TimeDiff.getTimeDifference(d1, d2)[field.ordinal()];
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #return The fields day, hour, minute, second and millisecond
*/
public static long[] getTimeDifference(Date d1, Date d2) {
long[] result = new long[5];
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(d1);
long t1 = cal.getTimeInMillis();
cal.setTime(d2);
long diff = Math.abs(cal.getTimeInMillis() - t1);
final int ONE_DAY = 1000 * 60 * 60 * 24;
final int ONE_HOUR = ONE_DAY / 24;
final int ONE_MINUTE = ONE_HOUR / 60;
final int ONE_SECOND = ONE_MINUTE / 60;
long d = diff / ONE_DAY;
diff %= ONE_DAY;
long h = diff / ONE_HOUR;
diff %= ONE_HOUR;
long m = diff / ONE_MINUTE;
diff %= ONE_MINUTE;
long s = diff / ONE_SECOND;
long ms = diff % ONE_SECOND;
result[0] = d;
result[1] = h;
result[2] = m;
result[3] = s;
result[4] = ms;
return result;
}
public static void printDiffs(long[] diffs) {
System.out.printf("Days: %3d\n", diffs[0]);
System.out.printf("Hours: %3d\n", diffs[1]);
System.out.printf("Minutes: %3d\n", diffs[2]);
System.out.printf("Seconds: %3d\n", diffs[3]);
System.out.printf("Milliseconds: %3d\n", diffs[4]);
}
public static enum TimeField {DAY,
HOUR,
MINUTE,
SECOND,
MILLISECOND;
}
}
// d1, d2 are dates
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.");
Joda-Time
Joda-Time 2.3 library offers already-debugged code for this chore.
Joad-Time includes three classes to represent a span of time: Period, Interval, and Duration. Period tracks a span as a number of months, days, hours, etc. (not tied to the timeline).
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yy/MM/dd HH:mm:ss" ).withZone( timeZone );
DateTime dateTimeStart = formatter.parseDateTime( "11/03/14 09:29:58" );
DateTime dateTimeStop = formatter.parseDateTime( "11/03/14 09:33:43" );
Period period = new Period( dateTimeStart, dateTimeStop );
PeriodFormatter periodFormatter = PeriodFormat.getDefault();
String output = periodFormatter.print( period );
System.out.println( "output: " + output );
When run…
output: 3 minutes and 45 seconds
Here is my code.
import java.util.Date;
// to calculate difference between two days
public class DateDifference {
// to calculate difference between two dates in milliseconds
public long getDateDiffInMsec(Date da, Date db) {
long diffMSec = 0;
diffMSec = db.getTime() - da.getTime();
return diffMSec;
}
// to convert Milliseconds into DD HH:MM:SS format.
public String getDateFromMsec(long diffMSec) {
int left = 0;
int ss = 0;
int mm = 0;
int hh = 0;
int dd = 0;
left = (int) (diffMSec / 1000);
ss = left % 60;
left = (int) left / 60;
if (left > 0) {
mm = left % 60;
left = (int) left / 60;
if (left > 0) {
hh = left % 24;
left = (int) left / 24;
if (left > 0) {
dd = left;
}
}
}
String diff = Integer.toString(dd) + " " + Integer.toString(hh) + ":"
+ Integer.toString(mm) + ":" + Integer.toString(ss);
return diff;
}
}
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
Well, I'll try yet another code sample:
/**
* Calculates the number of FULL days between to dates
* #param startDate must be before endDate
* #param endDate must be after startDate
* #return number of day between startDate and endDate
*/
public static int daysBetween(Calendar startDate, Calendar endDate) {
long start = startDate.getTimeInMillis();
long end = endDate.getTimeInMillis();
// It's only approximation due to several bugs (#see java.util.Date) and different precision in Calendar chosen
// by user (ex. day is time-quantum).
int presumedDays = (int) TimeUnit.MILLISECONDS.toDays(end - start);
startDate.add(Calendar.DAY_OF_MONTH, presumedDays);
// if we still didn't reach endDate try it with the step of one day
if (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
++presumedDays;
}
// if we crossed endDate then we must go back, because the boundary day haven't completed yet
if (startDate.after(endDate)) {
--presumedDays;
}
return presumedDays;
}
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);
You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter
Output:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)
As said before - think this is a good answer
/**
* #param d2 the later date
* #param d1 the earlier date
* #param timeUnit - Example Calendar.HOUR_OF_DAY
* #return
*/
public static int getTimeDifference(Date d2,Date d1, int timeUnit) {
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
if(timeUnit==Calendar.HOUR_OF_DAY)
return hours;
if(timeUnit==Calendar.MINUTE)
return minutes;
return seconds;
}

Categories

Resources