Friends,
I am looking to calculate the difference in days.
Hey suppose if I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day.
Please help me for this one.
Right now I am calculating the same using .getTimeInMillis() but it is not giving me expected results for the date condition mentioned above.
I you look for day and time difference then, use my code
public class AndroidWebImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Date sdate=Calendar.getInstance().getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
String setDate = "13/09/12 10:20:43";
Date AlarmDate=new Date(setDate);
String currentDate = format.format(sdate);
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(setDate);
d2 = format.parse(currentDate);
} catch (ParseException e) {
e.printStackTrace();
}
//Comparison
long diff = d1.getTime() - d2.getTime();
long diffSeconds = diff / 1000 % 60;
long days = (int) (diff / (1000 * 60 * 60 * 24));
long diffHours = (int) ((diff- (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
long diffMinutes = (int) (diff- (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * diffHours))/ (1000 * 60);
int curhour=sdate.getHours();
int curmin=sdate.getMinutes();
int alarmhour=AlarmDate.getHours();
int alarmmin=AlarmDate.getMinutes();
if(curhour==alarmhour && curmin==alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
else if(curhour>=alarmhour && curmin>=alarmmin || curhour<=alarmhour && curmin<=alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
}
}
You can't do this with millis, because you need to know where the day boundary falls (i.e. midnight). A millisecond either side of midnight means two different days.
You need to use a Calendar to determine how many days lie within the interval between your two dates. The JodaTime library has a lot of additional support for this kind of calculation.
See also Calculating the difference between two Java date instances
Your're just trying to find the number of days, right?
Try looking at this, it might have what you are looking for.
i made this code before, its may helps you
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* #author MErsan
*/
public class DateFormatter {
public static String formatDate(long time) {
StringBuilder result = new StringBuilder();
// 1- Check the year
// 2- Check the Month
// 3- Check the Day
// 4- Check the Hours
Date myDate = new Date(time);
Date todayDate = new Date(System.currentTimeMillis());
if (todayDate.getYear() - myDate.getYear() != 0) {
// Not same year, and should append the whole time
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
// Same Year
// now Check the month
if (todayDate.getMonth() - myDate.getMonth() != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Now Same Month
// Check the day
int daysDiff = todayDate.getDate() - myDate.getDate();
if (daysDiff == 1) {// Yesterday
result.append("Yesterday").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (daysDiff != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Same Day :')
// Check the hour
int hoursDiff = todayDate.getHours() - myDate.getHours();
if (hoursDiff < 0) {// Invalid Time
// :#
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
// current hour
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
result.append("Before").append(' ');
result.append(hoursDiff).append(' ');
result.append("Hours").append(' ');
result.append("and").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
System.err.println("Case 6");
return result.toString();
} else if (hoursDiff == 0) {// Same Hours
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
if (mintuesDiff < 1) {// Seconds Only {Same Minute}
int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
result.append("Before").append(' ');
result.append(Math.abs(secondsDiff)).append(' ');
result.append("Seconds");
return result.toString();
} else {
result.append("Before").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
return result.toString();
}
}
// Default
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
}
import java.util.Calendar;
public class DateDifference
{
public static void main(String[] args)
{
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 01, 10);
calendar2.set(2012, 07, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
}
}
You need to get rid of the timestamps and then subtract dates to get the difference in dates or you can use Joda-time as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
Date past = new Date(112, 8, 1);
Date today = new Date(112, 7, 30);
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays();
Re-post:
There's a simple solution, that at least for me, is the only feasible solution.
The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.
To count the actual number of days between startDate and endDate, simply do:
// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
// Find the difference, duh
long daysBetween = endDay - startDay;
This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).
Related
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;
}
Say I have 2 strings containing date as follow
String A = 25 Nov 2015 10.50 GMT+6
String B = 25 Nov 2015 10.45 GMT+6
How do I make it so that it is acceptable to have a differences of several minutes between the two date strings? I can't use Selenium to assert between the two strings as it would definitely throw me asserting error.
Parse the strings, then compare the milliseconds and apply a threshold.
But first, you have to fix those bad GMT offsets.
String a = "25 Nov 2015 10.50 GMT+6";
String b = "25 Nov 2015 10.45 GMT+6";
// fix bad GMT
a = a.replaceFirst(" GMT\\+(\\d)\\b", " GMT+0$1");
b = b.replaceFirst(" GMT\\+(\\d)\\b", " GMT+0$1");
// parse dates
SimpleDateFormat datefmt = new SimpleDateFormat("d MMM yyyy HH.mm 'GMT'X");
Date dateA = datefmt.parse(a);
Date dateB = datefmt.parse(b);
// detect difference
long diffInMillis = Math.abs(dateA.getTime() - dateB.getTime());
if (diffInMillis < 5 * 60 * 1000) {
// all is good
} else {
// bad: 5 or more minutes apart
}
YOu can use the below comparator to compare roughly equal dates. You can decide the delta for two dates being equal while instantiating the comparator.
public class RoughlyEqualDates implements Comparator<String> {
int acceptableDelta = 300000; // 5 minutes
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy HH:mm");//choose appropriate format here
RoughlyEqualDates(int deltaInMins){//configurable delta
this.acceptableDelta = deltaInMins*60*1000;
}
public int compare(String date1, String date2) {
long d1,d2;
try {
d1 = format.parse(date1).getTime();
d2 = format.parse(date2).getTime();
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
if(Math.abs(d1-d2)<=acceptableDelta){
return 0;
}else{
return d1>d2?1:-1;
}
}
}
The methods suggested are nice, though I believe you must be getting these strings from the Date itself in which case why not try this :
Date d1 = <source for String A>;
Date d2 = <source for String B>;
long diff = d2.getTime() - d1.getTime();
//here are the differences
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);
//for your case
if(diffMinutes <= acceptableDifference) //I' fine with it
else //Give me something else
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();
}
}
}
I have the following two methods:
private long getTimeInMilliseconds()
{
Calendar c = Calendar.getInstance();
if(c.get(Calendar.DAY_OF_MONTH) == 21)
{
c.set(Calendar.MONTH, Calendar.MONTH + 1 );
c.set(Calendar.DAY_OF_MONTH, 1);
}
else
c.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH + 10);
if(c.get(Calendar.MONTH) > 11)
c.set(Calendar.MONTH, 0);
return c.getTimeInMillis();
}
public static void remainingTime(L2PcInstance player)
{
long now = System.currentTimeMillis();
long then = player.getExpBoostTime();
long time = then - now;
int hours = (int) (time / 3600000);
player.sendMessage(hours+ " hours remaining until your EXP BOOST PERIOD ends");
}
I want getTimeInMillisSeconds() to return the time 10 days later. I want remainingTime() to show how many days (in hours) remain.
With the code above, it shows 4 days remaining and not 10.
Can anybody help?
You are making a mistake in the set() method.
It should be
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 10);
However, your approach is far from being the best. The one suggested in another answer (adding 10 * 24 * 60 * 60 * 1000 milliseconds to the current time) is far better IMHO.
The best way to get "ten days from now" is to use timestamps/milliseconds.
You can get the current time in milliseconds from a calendar like this:
Calendar someCalendar = new Calendar();
long someTimestamp = someCalendar.getTimeInMillis();
Once you get that, you can add ten days to it (again in milliseconds):
long tenDays = 1000 * 60 * 60 * 24 * 10;
long tenDaysFromNow = someTimestamp + tenDays;
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;
}