Getting incorrect results when calculating difference between two times - java

I am working on an android app to keep track of hours between signing in and out.
An employee can sign in one day and sign out the next day or within the same day.
Within the app, I have a function that should calculate the difference between two times.
But I am not getting the correct results...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mma");
Date start;
Date end;
double difference;
//Test 1
start = simpleDateFormat.parse("7:00AM");
end = simpleDateFormat.parse("3:30PM");
difference = end.getTime() - start.getTime();
Log.d("difference", String.valueOf(difference)); // 3.06E7
Log.d("Time difference", String.valueOf(((difference/1000)/60)/60));
//Prints '8.5' correct.
// Text 2
start = simpleDateFormat.parse("11:00PM");
end = simpleDateFormat.parse("7:30AM");
difference = end.getTime() - start.getTime();
Log.d("difference2", String.valueOf(difference)); // -5.58E7
Log.d("Time difference2", String.valueOf(((difference/1000)/60)/60));
//Prints '-15.5' but should print '8.5'
As you can see... the first test works correctly, yet the second test fails.
How can I resolve this issue?

Your current issue is that your are calculating the difference between two hours and these hours are technically on the same day.
You are currently calculating the time difference between (A) Day 1: 23:00 and (b) Day 1: 7:30. 7:30 is 15.5 hours before 23:00.
You will need to add your starting and ending dates.
Exemple:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date day1 = simpleDateFormat.parse("12/10/2017 23:00:00");
Date day2 = simpleDateFormat.parse("13/10/2017 07:30:00");
DateTime dt1 = new DateTime(day1);
DateTime dt2 = new DateTime(day2);
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes.");
// Should print "8 hours, 30 minutes.'

start is after end (on same day), hence a negative result; -15.5 + 24 == 8.5. A modulo 24 is in order:
difference = end.getTime() - start.getTime();
difference = difference/1000/60/60;
if (difference < 0) {
difference += 24;
}
Log.d("Time difference", String.valueOf(difference));

Related

how to increase date concerning a working week? [duplicate]

This question already has answers here:
How do I ignore weekends using the Java calendar?
(2 answers)
Closed 7 years ago.
I have a date in java, and I would like to add a certain amount of working time to it.
However, it should consider a working week.
8 Hours days (8:00 to 16:00),
and
no work on weekends (Saturday/Sunday).
So I have a Date object giving the current time. I also have a double, which are the minutes to be added to that date. What would be the best way of doing this?
I'm using Java 8.
Some examples:
Working on the same day:
Date date = new Date(2000, 1, 1, 8, 0); //so first of jan, 8:00. Let's assume this is a monday.
double minutes = 4 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the same day, 12:00
Working over multiple days:
Date date = new Date(2000, 1, 1, 14, 0); //so first of jan, 14:00. Let's assume this is a monday.
double minutes = 4 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the next day, 10:00
// 2 hours on the first day, the next two hours of work on the next.
Working over a weekend:
Date date = new Date(2000, 1, 5, 14, 0); //so fifth of jan, 14:00. Let's assume this is a friday.
double minutes = 8 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the next monday, 14:00
// 2 hours on the first day, the next six hours of work the next monday.
Thanks!
You can use this method:
public static LocalDateTime addWorkingMinutes(LocalDateTime date, long minutes) {
if (date.getHour() < 8) {
// Working day hasn't started. Reset date to start of this working day
date = date.withHour(8).withMinute(0).withSecond(0);
}
// Take care of weekends
if (date.getDayOfWeek() == DayOfWeek.SATURDAY) {
date = date.plusDays(2);
} else if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
date = date.plusDays(1);
}
LocalDateTime endOfCurrentWorkingDay = date.withHour(16).withMinute(0).withSecond(0);
// Get minutes from date to endOfCurrentWorkingDay
long minutesCovered = ChronoUnit.MINUTES.between(date, endOfCurrentWorkingDay);
if (minutesCovered > minutes) {
// If minutesCovered covers the minutes value passed, that means result is the same working
// day. Just add minutes and return
return date.plusMinutes(minutes);
} else {
// Calculate remainingMinutes, and then recursively call this method with next working day
long remainingMinutes = minutes - minutesCovered;
return addWorkingMinutes(endOfCurrentWorkingDay.plusDays(1).withHour(8), remainingMinutes);
}
}
tested with your sample input, and some other inputs on my end, considering weekends.
Note: I'm using Java 8 DateTime API, since you're already on Java 8, there shouldn't be any excuse to still use Date.

Unable to find difference between two dates w.r.t time,seconds,months and years?

This is my java class
public class dateparse {
public static void main(String args[]) throws ParseException
{
Date dd=new Date();
int year = Calendar.getInstance().get(Calendar.YEAR);
int month=0;
int calc_days=0;
String d1 = dd.getDate()+"/"+dd.getMonth()+"/"+year;
String d2 = "19/1/2014";
SimpleDateFormat s1 = new SimpleDateFormat("dd/mm/yyyy");
SimpleDateFormat s2 = new SimpleDateFormat("dd/mm/yyyy");
Date dateOne = new SimpleDateFormat("dd/mm/yyyy").parse(d1);
Date dateTwo = s2.parse(d2);
long diff = dateOne.getTime() - dateTwo.getTime();
calc_days= (int) (diff / 1000 / 60 / 60 / 24 / 1);
}
}
I am trying to find the difference between current date and the date specified with respect to seconds,minutes,hours,days,months and years.Here my input date is 19th Feb 2014.I want to show the difference in no of days(e.g. 10 days) or months+days(e.g.1 month and 2 days) or year+month+days(e.g. 1 year and 2 months and 4 days).But when I run this code it returns difference as -10 days.
Your error is your parsing. Lowercase m means minutes, not month:
SimpleDateFormat s2 = new SimpleDateFormat("dd/mm/yyyy");
should be:
SimpleDateFormat s2 = new SimpleDateFormat("dd/MM/yyyy");
Here's a simplified example:
String d1 = "21/1/2014";
String d2 = "19/1/2014";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date dateOne = sdf.parse(d1);
Date dateTwo = sdf.parse(d2);
long diff = dateOne.getTime() - dateTwo.getTime();
int differenceInDays = (int) (diff / 1000 / 60 / 60 / 24 / 1);
System.out.println(differenceInDays);
Prints: 2
This is a classic error caused by the horrible API that Java has provided:
date.getMonth() returns 0 for January, 1 for february... and 11 for December. If you can, try to avoid java.util.Date and Calendar :P
Attention - Accepted answer is wrong! Prove:
Use as input the dates 2014-03-19 and 2014-04-01 in my timezone "Europe/Berlin". The true answer is 13 days as everyone can easily veryify using standard calendars, but the accepted code of #Duncan produces 12 days because in my timezone there was a dst-jump which breaks the basis of calculation formular (1 day = 24 hours). On 30th of March the day was only 23 hours long.
The JDK pre 8 does not offer a built-in generic solution for this problem. Please also note that your input is just a pair of two plain dates with no time. Therefore it is silly to ask for the difference in seconds, etc. Only asking for the difference in days, months, weeks or years is sensible. In Java 8 you can do following:
// only days
LocalDate start = LocalDate.of(2014, 3, 19); // start in March
LocalDate end = LocalDate.of(2014, 4, 1);
int days = ChronoUnit.DAYS.between(start, end); // 13
// period in years, months and days
LocalDate start = LocalDate.of(2014, 2, 19); // start in February
LocalDate end = LocalDate.of(2014, 4, 1);
Period period = Period.between(start, end); // P1M13D = 1 month + 13 days
Unfortunately you are not free to choose in which calendar units you like to get the difference expressed. JodaTime (and my library) has a more flexible approach using PeriodType.

Can't get the number of days between 2 months - specific case

I have few dates in this format: 31/08/13 and I'm getting tehm from an xls file
What I need to do is to get the previous month and to calculate the days betwen these dates. I really don't know what to do.
Here is what I have tried:
code edited*
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.setTime(row.getCell(0).getDateCellValue());
start.add(start.MONTH,-1);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
if(diffDays < 0){
System.out.println(Math.abs(diffDays));
}
DateFormat dateFormatw = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormatw.format(startDate)+" and "+
dateFormatw.format(endDate)+" is "+
diffDays+" days.");
But it seems wrong. I really can't get my mind on it as I'm so tired. I lost too many hours on this without luck.
I'm trying to get the same date but one month ago and to calculate the days, between these 2 dates endTime and startTime
Please help me!
I don't know what a ProdCalendar is, it's presumably something internal to your project. But the simple way to get the numbers of days between 2 dates, which is (I think) what you want, is this:
//First date
Date d1 = dateFormat.parse("31-10-13");
//Second date
Date d2 = dateFormat.parse("31-08-13");
//Interval:
long intervalMs = d1.getTime() - d2.getTime();
long intervalDays = intervalMs/(1000*60*60*24);
In your code, date22 is initialised just with new date() so it will be the current system time. You are comparing that (in a depracated way) to a date retrieved from the spreadsheet. I also notice that Calendar cal in this line near the start:
Calendar cal = Calendar.getInstance();
cal.setTime(row.getCell(0).getDateCellValue());
Is not used again, so appears to be redundant.
Your code is more complicated than it needs to be, so you need to step back and think about what you want to achieve. Simple code is good code.

Date difference in Java 23 hours day

I have to calculate the difference between to dates, I have found a way but I have this strange result, Am I missing something?
public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long result = format.parse("2012-03-25 24:00").getTime() - format.parse("2012-03-25 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
result = format.parse("2012-03-26 24:00").getTime() - format.parse("2012-03-26 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
}
This is the result:
Difference in hours: 23
Difference in hours: 24
Thanks for the advices, now I'm using the Joda libray, I have this question, when I calculate the difference in this way:
DateTime begin = new DateTime("2012-03-25T00:00+01:00");
DateTime end = new DateTime("2012-03-26T00:00+01:00");
Hours m = Hours.hoursBetween(begin, end);
If I use this way to calculate the hours I get 24 hours (because the DST is not considered I assume)
What class/calculus should I use in order to get as result the 23 hours considering the DST (I have already tried different ways but I don't get it) the Period class?
Thanks for all the help...
Chances are you happen to have picked a date where daylight saving time changed in that time zone, so the day could really have been only 23 hours long. (March 25th 2012 certainly was the DST change date for Europe, e.g. Europe/London. We don't know what your default time zone is though.)
If you set your date format to use UTC, you shouldn't see this effect. (It's somewhat odd to use 24:00 in a string representation, mind you.) It's not clear what your data is meant to represent though, or what you're trying to measure. You should work out what time zone your data is really meant to be in, if you want to work out how much time actually elapsed between those local times.
(As noted in another answer, Joda Time is a much better API in general - but you still need to know how to use it properly, and when trying to work out the actual elapsed time, you'd still have seen the same results here.)
Must place the library file like explained below.
import java.util.Date;
String dateStart = dateChooserCombo1.getText();
String dateStop =dateChooserCombo2.getText();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
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, ");
jTextField3.setText(""+diffDays);
} catch (Exception e) {
e.printStackTrace();
}

Time Duration problem

I am not able to get the correct Time duration.So can anyone please help me in finding the solution
//code
public static String getDateDifference(java.util.Date start, java.util.Date end) {
logger.info("Enter getDateDifference ");
Calendar startCal = Calendar.getInstance();
startCal.setTime(start);
Calendar endCal = Calendar.getInstance();
endCal.setTime(end);
int hourDiff = Math.abs(endCal.get(Calendar.HOUR_OF_DAY) - startCal.get(Calendar.HOUR_OF_DAY));
int minDiff = Math.abs(endCal.get(Calendar.MINUTE) - startCal.get(Calendar.MINUTE));
String diff = Integer.toString(hourDiff) + ":" + Integer.toString(minDiff);
logger.info("Date Difference : " + diff);
logger.info("Exit getDateDifference ");
return diff;
}
Won't this fail if the start is 23:59 and the end 00:01?
Instead just get the milliseconds from the two dates, subtract and then convert to hours and minutes.
long millis = end.getTime() - start.getTime();
long seconds = millis/1000L;
long hours = seconds/3600L;
long mins = (seconds % 3600L) / 60L;
If you can use JodaTime this becomes fairly trivial. Like so:
Period period = new Period( new DateTime( start ), new DateTime( end ), PeriodType.time() );
return period.getHours() + ":" + period.getMinutes();
why don't you do the following
1) convert your 2 Dates to a common unit (here hours)
2) calculate the difference
3) transform the result to a format you want (Date, string ...)
I don't have the code handy but it should be fairly straight forwards.
your method is open to small errors like forgetting to increment/decrement a day when you go above 24h or under 0h.
also it will be diffcult to maintain if you want to suddenly add minutes and seconds ...
hope this helps
Jason

Categories

Resources