Java Date difference in terms of days [duplicate] - java

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 7 years ago.
Could anyone please help me out for calculating Date difference in terms of no of days in an efficient way?
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;

//diff in msec
long diff = currentDate.getTime() - nextCollectionDate.getTime();
//diff in days
long days = diff / (24 * 60 * 60 * 1000);

You can use JodaTime which is a very useful API for these scenarios
int days = Days.daysBetween(date1, date2).getDays();
or else you can create your own method and get the difference
public long getDays(Date d1, Date d2)
{
long l = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}

I would suggest you to use LocalDate in Java 8:
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println("No of days: " + days);
which as expected will print:
No of days: 1

You can use joda api
Below code should solve your query
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
Days d = Days.daysBetween(new DateTime(nextCollectionDate ), new DateTime(currentDate ))
int daysDiff = d.getDays();

Related

Android Compare epoch time and today date and output the difference [duplicate]

This question already has answers here:
How can I convert a Unix timestamp to DateTime and vice versa?
(21 answers)
Closed 6 years ago.
I need to calculate a expiry date difference.
I will get this epoch time:
1481410800 (06-Dec-2016 (14:42))
now I want to calculate the days until the expiry date (1481410800)
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy (HH:mm)", Locale.getDefault());
//Expiry Date
long unixSecondsExpiry = 1481410800; //unixSeconds
Date expiryDate = new Date(unixSecondsExpiry*1000L);
long currentDate = now.get(Calendar.SECOND);
long diff = unixSecondsExpiry - currentDate;
long days = diff / (24l * 60l * 60l * 1000l);
String formattedExpiryDate = sdf.format(expiryDate);
String formattedDateNow = sdf.format(new Date());
Log.w("RUNTEST", "formattedDateNow: " + formattedDateNow);
Log.w("RUNTEST", "formattedExpiryDate: " + formattedExpiryDate);
Log.w("RUNTEST", "days: " + days);
I keep getting 17 days but it should be 5 days till expiry.
RUNTEST: formattedDateNow: 06-Dec-2016 (14:42)
RUNTEST: formattedExpiryDate: 11-Dec-2016 (07:00)
RUNTEST: days: 17
Here you are using new Date()
String formattedDateNow = sdf.format(new Date());
but the calculation is using
long currentDate = now.get(Calendar.SECOND);
Why not just use
long currentDate = new Date().getTime ();
edit
getting the SECONDS from a calendar is just getting the current seconds counter
Field number for get and set indicating the second within the minute.
E.g., at 10:04:15.250 PM the SECOND is 15.

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

How to calculate difference in days between two dateboxes in GWT? [duplicate]

This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have 1 datebox (datebox1) in my GWT application, which allows users to set the date in past.
Datebox1 is set to following format (not that it probably matters):
datebox1.setFormat(new DateBox.DefaultFormat (DateTimeFormat.getFormat("EEE, MMM dd, yyyy")));
How do I programatically calculate the difference in days between the date selected in the date box and the current date.
I can't find much on the net and would appreciate a simple example.
The simplest way:
Date currentDate = new Date();
int daysBetween = CalendarUtil.getDaysBetween(myDatePicker.getValue(), currentDate);
the below code block will be useful for you
Date selectedDate = DateBox.getDatePicker().getValue();
Date currentDate= new Date();
long fromDate = selectedDate.getTime();
long toDate = currentDate.getTime();
long diffGap = toDate - fromDate;
long diffDays = diffGap / (24 * 60 * 60 * 1000);
If you know how to extract date from your textbox, you can use the following function to get the time difference between any two dates
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}

Date difference calculation in Java [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 9 years ago.
I want to calculate the difference between two dates.
Currently, I am doing:
Calendar firstDate = Calendar.getInstance();
firstDate.set(Calendar.DATE, 15);
firstDate.set(Calendar.MONTH, 4);
firstDate.get(Calendar.YEAR);
int diff = (new Date().getTime - firstDate.getTime)/(1000 * 60 * 60 * 24)
This gives me output 0. But I want that I should get the output 0 when the new Date() is 15. Currently the new date is 14. It makes my further calculation wrong and I am confused how to resolve this. Please suggest.
Finding the difference between two dates isn't as straightforward as
subtracting the two dates and dividing the result by (24 * 60 * 60 *
1000). Infact, its erroneous!
/* Using Calendar - THE CORRECT (& Faster) WAY**/
//assert: startDate must be before endDate
public static long daysBetween(final Calendar startDate, final Calendar endDate) {
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
long endInstant = endDate.getTimeInMillis();
int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);
Calendar cursor = (Calendar) startDate.clone();
cursor.add(Calendar.DAY_OF_YEAR, presumedDays);
long instant = cursor.getTimeInMillis();
if (instant == endInstant)
return presumedDays;
final int step = instant < endInstant ? 1 : -1;
do {
cursor.add(Calendar.DAY_OF_MONTH, step);
presumedDays += step;
} while (cursor.getTimeInMillis() != endInstant);
return presumedDays;
}
You can read more on this here.
I don't think that by creating a new Date() will give you the current time and date instead do this:
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
Date firstDate = new Date();
firstDate.setHour(...);
firstDate.setMinute(...);
firstDate.setSeconds(...);
long dif = currentDate.getTime() - firstDate.getTime();
So as you can see you can be as straightforward as subtracting one from another...

How can I calculate the difference between two dates [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I calculate someone's age in Java?
I have two dates eg 19/03/1950 and 18/04/2011. how can i calculate the difference between them to get the person's age? do I have to keep multiplying to get the hours or seconds etc?
String date1 = "26/02/2011";
String date2 = "27/02/2011";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
You use the classes Date and Duration:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Date.html
http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html
You create Date-objects, then use Duration's methods addTo() and subtract()
The following code will give you difference between two dates:
import java.util.Date;
import java.util.GregorianCalendar;
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
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.");
}
}
Why not use jodatime? It's much easier to calculate date and time in java.
You can get the year and use the method yearsBetween()

Categories

Resources