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

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);
}

Related

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.

Converting date to this format: "X years, X months, X days..."

I am creating a Calendar instance, and setting the date to July 1, 1997 like so:
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(1997, 6, 1);
What I want to do, is that without using an external library, get the following output from that date (proper calculating of leap years / seconds would be good, but not required) prior to current date (e.g. November 1, 2015 02:45:30):
18 years, 4 months, 0 days, 2 hours, 45 minutes, 30 seconds
I am not quite sure if this is possible at all. I've tried some weird, not very logical calculations, which needed lots of improvements, but couldn't make it work:
int years = currentYear - calendar.get(Calendar.YEAR);
int months = calendar.get(Calendar.MONTH);
if(currentMonth > months) {
years -= 1;
}
UPDATE - Code until now:
Calendar currentDate = Calendar.getInstance();
currentDate.clear();
Calendar birthDate = Calendar.getInstance();
birthDate.clear();
birthDate.set(this.birthYear, this.birthMonth - 1, this.birthDay);
Calendar date = Calendar.getInstance();
date.clear();
date.setTimeInMillis(birthDate.getTimeInMillis() - currentDate.getTimeInMillis());
System.out.println(Integer.toString(date.get(Calendar.YEAR)));
if you are using java 8 then you have LocalDateTime and PlainTimeStamp classes to use
here you find some answers Java 8: Calculate difference between two LocalDateTime
This might help
Calendar startCalendar = Calendar.getInstance();
startCalendar.clear();
startCalendar.set(1997, 6, 1);
Date start = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
// endCalendar.clear();
// endCalendar.set(2015, 10, 1);
Date end = endCalendar.getTime();
long diff = end.getTime() - start.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff) % TimeUnit.DAYS.toHours(1);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff) % TimeUnit.HOURS.toMinutes(1);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff) % TimeUnit.MINUTES.toSeconds(1);
System.out.println(days + " " + hours + " " + minutes + " " + seconds);
from the days we can write the logic to find the number of leap years, months using modulo division
Java 8 has a new Date API you can try that too since you're using Java 8

Subtracting dates and get difference in days.How to subtract them? [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
can anyone tell how to subtract string "after" from "today" to get days difference.
import java.text.*;
import java.util.*;
public class Main {
public static void main(String args[]){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
}
}
It would be easier with java8 where you dont need to subtract long values represent of date and change back to days, hours and minutes.
Date today= LocalDate.now();
Date futureDate = LocalDate.now().plusDays(1);
long days = Period.between(today, futureDate).getDays();
Period & LocalDate class are available in #java8
LocalDate docs
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day. Other date fields, such as
day-of-year, day-of-week and week-of-year, can also be accessed. For
example, the value "2nd October 2007" can be stored in a LocalDate.
If you are not using java8, use joda-time library's org.joda.time.Days utility to calculate this
Days day = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Using JodaTime, in case you don't have Java 8
String timeValue = "2014/11/11";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd").toFormatter();
LocalDate startDate = LocalDate.parse(timeValue, parseFormat);
LocalDate endDate = startDate.plusDays(20);
System.out.println(startDate + "; " + endDate);
Period p = new Period(startDate, endDate);
System.out.println("Days = " + p.getDays());
System.out.println("Weeks = " + p.getWeeks());
System.out.println("Months = " + p.getMonths());
Which outputs...
2014-11-11; 2014-12-01
Days = 6
Weeks = 2
Months = 0
try this...
May it helps you.
import java.util.Date;
import java.util.GregorianCalendar;
// compute the difference between two dates.
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2010, 10, 10, 11, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
This may help You..
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
Date d1 = null;
Date d2 = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try {
d1 = format.parse(today);
d2 = format.parse(After);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Difference is "+diffDays+" Days");

Java subtract two dates in this format [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating difference in dates in Java
How do you subtract Dates in Java?
I am parsing two dates from a string that look like:
Oct 15, 2012 1:07:13 PM
Oct 23, 2012 03:43:34 PM
What I need to do is find the difference between these two dates, ex:
Oct 23, 2012 03:43:34 PM - Oct 15, 2012 1:07:13 PM
= 8 days 2 hours 36 minutes 21 seconds
^ This is what I need to get with the two date/times I have
I believe I need to parse the format and convert it to another format, then subtract the difference between and do the math to get the days/hours/minutes/seconds between
In contrary to what other answerers try to imply, calculating the difference between two dates isn't that trivial in standard Java SE.
Your first step is indeed to convert those strings to useable Date instances. You can do this using SimpleDateFormat. Here's a kickoff example:
String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";
SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.ENGLISH);
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
(please note the importance of the optional Locale argument here, this is often overlooked in answers about converting strings to dates)
Your next step is calculating the difference between those 2 dates. This is a terrible job when you are restricted to the standard Java SE API. Best what you can get is the java.util.Calendar.
Note that you could of course substract the milliseconds and calculate the difference using the usual arithmetic operators.
long differenceInMillis = date2.getTime() - date1.getTime();
// ...
But this naive approach doesn't take leap years into account, let alone daylight saving time and local-specific changes in datetime.
As to the java.util.Calendar approach, you basically need to use Calendar#add() in a counter loop to get the elapsed value for years, months and days. This takes leap years, daylight saving time and local-specific disturbances in time properly into account.
First create this helper method to eliminate some boilerplate code:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
Now you can calculate the elapsed time as follows:
Calendar start = Calendar.getInstance();
start.setTime(date1);
Calendar end = Calendar.getInstance();
end.setTime(date2);
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone(); // Otherwise changes are been reflected.
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
System.out.format("%d years, %d months, %d days, %d hours, %d minutes, %d seconds", elapsed);
Pretty ugly, yeah.
If you going to work with date and time in Java pretty often, then you may find Joda time the walhalla. Here's a concrete kickoff example of how you could do it all with pure Joda Time:
String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";
DateTimeFormatter dtf = DateTimeFormat.forPattern("MMM d, yyyy h:mm:ss a").withLocale(Locale.ENGLISH);
DateTime dateTime1 = dtf.parseDateTime(string1);
DateTime dateTime2 = dtf.parseDateTime(string2);
Period period = new Period(dateTime1, dateTime2);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" years ")
.appendMonths().appendSuffix(" months ")
.appendWeeks().appendSuffix(" weeks ")
.appendDays().appendSuffix(" days ")
.appendHours().appendSuffix(" hours ")
.appendMinutes().appendSuffix(" minutes ")
.appendSeconds().appendSuffix(" seconds ")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed);
Much better, right? The plural "s" needs some work though, but that's beyond the question.
You need to use SimpleDateFormat to parse String and create Date
Then you can find the difference between dates.
Here is javadoc for SimpleDateFormat
try this:
Calendar ca1 = Calendar.getInstance();
ca1.set(2012,05,25);
// Addition of date in java
ca1.add(Calendar.DATE, 23); // Add 23 days in Dates in Calendar
ca1.add(Calendar.MONTH, 2); // Add 2 Month in Date in Calendar
ca1.add(Calendar.YEAR, 4); // add 4 Year in Date in Calendar
ca1.add(Calendar.DATE, -23); // sub 23 days in Dates in Calendar
ca1.add(Calendar.MONTH, -2); // sub 2 Month in Date in Calendar
ca1.add(Calendar.YEAR, -4); // sub 4 Year in Date in Calendar

What is the equivalent of getTime(), which is a method in Date, in joda.time.LocalDate?

I was doing a simple calculation to get the difference between two dates. If I was using a Date class I can do like this:
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
But I couldn't find a method like getTime() in Local date. Is there any way so I can easily get what I am trying to achieve?
I even tried to change my LocalDate object to a temporary date object like this:
LocalDate date=new LocalDate();
Date d=date.toDate();
but the method toDate() isnt working . i.e it says it is not recognized method.(so compile time error) but from what I can see it is in the Documentation
Thank you for your time and of course happy Thanksgiving.
Days.daysBetween() is the answer.
LocalDate now = new LocalDate();
LocalDate past = now.minusDays(300);
int days = Days.daysBetween(past,now).getDays();
Never convert a LocalDate to a Java Date (two completey different beasts) if you are just dealing with dates. A Jodatime Localdate is a true "Calendar date", i.e. , a tuple of {day,month,year} (together with a Gregorian calendar specification), and has nothing to do with "physical time", with seconds, hours, etc. If you need to do dates arithmetic, stick with Localdate and you'll never need to worry about stupid bugs (timezones, DST, etc) which could arise if you dates arithmetic using java Dates.
Try something like this:
LocalDate date = new LocalDate();
Date utilDate = date.toDateTimeAtStartOfDay( timeZone ).toDate( );
or refer to this post
How to convert Joda LocalDate to java.util.Date?
I tested this sample code to find out the difference in days, you can find the difference as per your needs.
Please see http://joda-time.sourceforge.net/key_period.html
LocalDate currentDate = new LocalDate();
LocalDate previousDate = currentDate.minusDays(1);
System.out.println(currentDate);
System.out.println(previousDate);
Period periodDifference = new Period(currentDate, previousDate, PeriodType.days());
System.out.println(periodDifference);
private long diff(Calendar c1, Calendar c2) {
long d1 = c1.getTimeInMillis();
long d2 = c2.getTimeInMillis();
return ((d2 - d1) / (60*60*24*1000));
}
Have not found any equivalents for LocalDate as they are not exact.
But there are several equivalents for LocalDateTime:
LocalDateTime localDateTime = LocalDateTime.now();
long longValue = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
or
long longValue = Timestamp.valueOf(localDateTime).getTime();

Categories