Calculating days between two dates wrong output - java

There are a lot of replicate questions on this matter, I've looked through most of them and got to make my code, but it didn't work.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
String targetDate = "18/05/2015";
date2.setTime(formatter.parse(targetDate));
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
long daysPassed = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
System.out.println("Today is : "+formatter.format(date1.getTime()));
System.out.println("Target date is : "+targetDate);
System.out.println("Difference of days between them is : "+daysPassed);
With the output being :
//Today is : 17/05/2015
//Target date is : 18/05/2015
//Difference of days between them is : 0
It works but with a day less, I could just add +1, but it gives 0 if is the same day too so there's that...
I should say It's for a uni project and I can't use external libraries or something that hasn't been taught yet.
It also gives an annoying parse exception error that keeps going all over the code

If you output the timeInMillis of date1 and date2, you'll get 2 long values, for example:
1431964800000
1431916207715
and the diff is 48592285
This value can be explained as:
48592285 milliseconds
48592285/1000 = 48592.285 seconds
48592285/1000/60 = 809.87 minutes
48592285/1000/60/60 = 13.50 hours
48592285/1000/60/60/24 = 0.56 days
That's the reason why you got 0 between 2 dates you specified.

Related

Converting difference between 2 dates to days in java 7 [duplicate]

This question already has answers here:
Calculating days between two dates with Java
(16 answers)
Closed 3 years ago.
I want to compare 2 dates in java and need to convert the difference between the 2 dates to days
//Setting up date
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 16);
Date d = cal.getTime();
Output would be something like this : Sun Jun 16 11:04:57 UTC 2019
//Getting the current date instance
Calendar cal1 = Calendar.getInstance();
Date d1 = cal1.getTime();
Output would be something like this : Mon Jul 08 11:04:57 UTC 2019
Need to get the difference between d & d1 in days.
Thanks in advance for taking your time to provide solution
Here, you just have to do simple math.
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
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);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormat.format(startDate)+" and "+
dateFormat.format(endDate)+" is "+
diffDays+" days.");
This will not work when crossing daylight savings time (or leap seconds) and might as well not give the expected results when using different times of day. You can modify it like this:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
diffDays--;
}
Hope this helps. Good luck.
Simplest way:
public static long getDifferenceDays(Date d, Date d1) {
long diff = d1.getTime() - d.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

Span in days between two dates misunderstanding

I have a misundertood managing dates in Java when I want to calculate the span in number of days between two dates.
Say we have two different dates:
Date 1: 1986-01-24
Date 2: 2017-04-20
Case 1: I have this snippet of code using Dates:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dt1 = format.parse("1986-01-24");
Date dt2 = format.parse("2017-04-20");
int intSpanInDays= (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println("Days between: " + intSpanInDays);
Output 1:
Days between: 11408
Case 2: Snippet of code using Calendar:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse("1986-01-24"));
cal1.set(Calendar.HOUR, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(format.parse("2017-04-20"));
cal2.set(Calendar.HOUR, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
long spanInMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();
GregorianCalendar cal3 = new GregorianCalendar();
cal3.setTimeInMillis(spanInMillis);
long millisInADay = 1000 * 60 * 60 * 24;
System.out.println("Days between: " + (cal3.getTimeInMillis() / millisInADay));
Output 2:
Days between: 11408
Case 3: Example using a spreadsheet in Excel:
When I use MS Excel to get this span just introducing the given dates and simply substracting, the output is this:
QUESTION
Why is Java calculation code of date missing one day? What is missing or wrong in either case 1 and 2 that does not match the result in case 3?
The spreadsheet is taking Daylight Savings into account, and your calculations are naively truncating, and given that there's one more 23-hour day in the interval than 25-hour days, the 23-hour remainder is truncated, yielding a result one day less than the correct answer.
JDK 8 largely simplifies these calculations with its new date time API. The same can be done accurately and simply using the below code :
LocalDate date1 = LocalDate.of(1986, 01, 24);
LocalDate date2 = LocalDate.of(2017, 04, 20);
System.out.println(date1.until(date2, ChronoUnit.DAYS));
This automatically takes care of any/all the DST changes, leap years etc. which is mostly missed when trying to do the calculations manually.

Difference between 2 dates in months and days in Java 7

I want to calculate the difference between 2 dates in months and days, I don't want to consider a month is 30 days and get the time in milliseconds and convert them, and I don't want to use a library such as Joda, and I also found a solution that uses LocalDate, however I am using Java 7.
I looked for answers to my question but could not find any, and I tried many approaches, I tried creating a calendar and passed the time in milliseconds the difference between my 2 dates, but if I tried for example getting the difference between 15/04 and 15/5 I would get 30 days and not 1 month, below is the code
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.APRIL);
c.set(Calendar.DAY_OF_MONTH, 15);
Date startDate = c.getTime();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 15);
Date lastDate = c.getTime();
Calendar diffCal = Calendar.getInstance();
diffCal.setTimeInMillis(lastDate.getTime() - startDate.getTime());
int months = ((diffCal.get(Calendar.YEAR) - 1970) * 12) + diffCal.get(Calendar.MONTH);
int days = diffCal.get(Calendar.DAY_OF_MONTH) - 1;
System.out.println("month(s) = " + months); // month(s) = 0
System.out.println("day(s) = " + days); // day(s) = 30
What can I use to get the difference in months first then in days between 2 dates?
EDIT: I wrote the below code and seems to give me what I want, could this be used
Date startDate = sdf.parse("31/05/2016");
Date endDate = sdf.parse("1/06/2016");
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
int months = 0, days = 0;
months += ((endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR)) * 12);
int startDays = startCalendar.get(Calendar.DAY_OF_MONTH);
int endDays = endCalendar.get(Calendar.DAY_OF_MONTH);
if(endDays >= startDays) {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH));
days += (endDays - startDays);
} else {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH) - 1);
days += ((startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) - startDays) + endDays);
}
System.out.println("Difference");
System.out.println("Month(s): " + months);
System.out.println("Day(s): " + days);
You answered your own question in your research. JDK7 does not support what you want. You have three options:
Write your own (do not do this because you will make many mistakes that have been made before)
Use a library like Joda-Time which has been recommended many times
Upgrade to JDK8 and use java.time.Period

How to calculate remaining days?

private long calculateRemainingDays() {
final Calendar c = Calendar.getInstance();
c.set(2015, 7, 23);
final Calendar today = Calendar.getInstance();
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
// Convert to days
final long days = millis / 86400000;
return days;
}
I need to add a function in my android application. I want a remaining days from current day to 2015/9/30. When the date is change to next day, the remaining days will decrease. I would like to say like that:
7 days remaining... 6/5/4/etc... Please help me to get correct remaining days. Sorry for my poor english. Thanks!
Use Calender.JULY instead of 7 in the parameters for the set() method.
7 = August.
6 = July.
As it starts with January as 0. It's better to use the static instance variables like Calender.JANUARY.
But as you want to calculate till 2015/9/30, you should set the value as
c.set(2015, Calender.SEPTEMBER, 09);
The rest of the code seems ok. It will return the correct number of days.
Try this :-
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
System.out.println ("Days: " + TimeUnit.DAYS.convert(millis , TimeUnit.MILLISECONDS));
if you don't mind using joda.time
you can do something of this form:
final Calendar c = Calendar.getInstance();
c.set(2015, Calender.SEPTEMBER, 30);
Date endDate = c.getTime();
Instant startInstant = new Instant(new Date());
Instant endInstant = new Instant(endDate);
Days days = Days.daysBetween(startInstant, endInstant);

Convert Excel timestamp to java.sql.date

I am extracting a timestamp out of Excel (2010):
It is displayed as "10.06.2015 14:24". The "internal representation" of excel is "42165.6". Last one is outputted from Excel.
So, for now, I want to parse this timestamp into a Java program like this:
double input = 42165.6;
// long myLong = ???
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println(sdf.format(new java.sql.Date(myLong)));
How can I do this in line 2?!
Many thanks for your help!!!
Kind regards
Excel stores dates as the number of days since January 1900. This makes it awkward to convert into a Java date (milliseconds since 1 Jan 1970). If you cannot export it in a readable format, you'll need to create a Java Calendar, set it to 1 Jan 1900, and add the number of days.
Here it is:
double excelDate = 42165.6;
int days = (int) excelDate; //number of days
int seconds = (int) ((excelDate-days) * 86400); //number of seconds in .6 days
//create calendar set to 01-Jan-1900
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1900);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
//Add days and seconds to get required date/time
cal.add(Calendar.DATE, days-1);
cal.add(Calendar.SECOND, seconds);
//cal.getTime() returns a java.util.Date, print it out...
System.out.println(cal.getTime());
NOTE
A java.sql.Date can be created from a java.util.Date as follows:
java.util.Date utilDate = ....
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
The fastest way to get from the excel notation to a java.sql.Date is:
double excelInput = 42165.6;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println("---> "
+ sdf.format(new java.sql.Date(
(long) ((excelInput - 25569) * 86400 * 1000))));
Excel stores a date since 01-01-1900, java.sql.date since 01-01-1970. There are exactly 25569 days difference between both dates. The constructor of java.sql.Date wants the milliseconds (!) since 01-01-1970, so with "* 86400" we get the seconds and then with (* 1000) the milliseconds.
That's it! ;)
Putting 42165.6 in excel and formatting to a date gives the correct date 6/10/15 14:24.
For me the answers by mrbela and NickJ both gave incorrect answers to the question of 42165.6, 06/10/2015 09:23 and 06/12/2015 03:25. This seems to be true of most of the examples I've tried.
The solution that worked for me was to use Apache POI, which is a java API for Microsoft Documents. This question is very similar and had the pointers that led me to poi.
Here is a working code example.
double input = 42165.6;
Date date = DateUtil.getJavaDate(input);
System.out.println(new SimpleDateFormat("dd.MM.yyyy HH:mm").format(javaDate));
which outputs the correct 06/10/2015 14:24

Categories