Javafx Using Date Picker - java

I am creating a Java Fx Application using Scene Builder. I have two Date Pickers Date1 and Date Two. I need to count the number of days between Date1 and Date2 excluding any Sunday. I have searched various answers but none that caters.
Any help much appreciated.

The following should work.
long date1 = datePicker1.getvalue().toEpochDay();
long date2 = datePicker2.getvalue().toEpochDay();
int days = (int) Math.abs(date1 - date2);
Example:
long date1 = 16322; // 09/09/2014
long date2 = 16329; // 09/16/2014
int days = (int) Math.abs(date1 - date2);
System.out.println(days); // 7 Days
Note: I do not think jfx2.0 has a built-in DatePicker, so I am assuming you are using jdk8.
Also, I pulled the the datePicker.getvalue().toEpochDay() logic from this question:
Stack Overflow: Get value from Date picker; which deals with jfx8.
The epoch in the LocalDate.toEpochDay() is the number of days since 01/01/1970.
Extra Credit
To Answer you question from the comment below, you could do the following.
int days = daysBetween(
datePicker1.getvalue(),
datePicker2.getvalue(),
Arrays.asList(DayOfWeek.SUNDAY)
);
public static int daysBetween(LocalDate start, LocalDate end, List<DayOfWeek> ignore) {
int count = 0;
LocalDate curr = start.plusDays(0); // Create copy.
while (curr.isBefore(end)) {
if (!ignore.contains(curr.getDayOfWeek()))
count++;
curr = curr.plusDays(1); // Increment by a day.
}
return count;
}

Related

Java - get number of days between dates [duplicate]

This question already has answers here:
Calculating days between two dates with Java
(16 answers)
Closed 5 years ago.
I've got a list of dates in format "yyyy-MM-dd", I'd like to have a number of days between my today date "2017-04-15" and first date from list which is higher than mine today date.
I am assuming that your events are not sorted by date. I am assuming that you can use Java 8. This is one of the tasks that have become so much easier with the java.time classes introduced in Java 8 (and backported to Java 6 and 7).
Use LocalDate.now() to get today’s date.
Iterate through your events, all the time keeping track of the closest future event date. For each event use LocalDate.parse() to convert the event’s date to a LocalDate. The 1-arg parse method fits your format. Compare with today’s date and with the earliest future event date encountered so far; if between, store as the new closest date. Use isAfter() and/or isBefore for the comparisons.
After your loop, you will either know the date or you will know that there are no future events at all. In the former case, use ChronoUnit.DAYS.between() to get the number of days from the current date to the event date.
Solution 1
If you are using joda library, then it will be easy, you can use Days.daysBetween :
Date startDate = ...;
Date endDate = ...;
int nbrDays = Days.daysBetween(new LocalDate(startDate), new LocalDate(endDate)).getDays();
Solution 2
Date startDate = ...;
Date endDate = ...;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
int day1 = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(endDate);
int day2 = cal.get(Calendar.DAY_OF_MONTH);
int nbrDays = day1 - day2;
System.out.println(nbrDays);
You have to import :
import java.util.Calendar;
import java.util.Date;
Solution 3
If your dates are in this format "yyyy-MM-dd" so you can have two dates like this :
String date1 = "1991-07-03";
String date2 = "2017-04-15";
What you should to do, split your dates with - :
String spl1[] = date1.split("-");
String spl2[] = date2.split("-");
Calculate the difference between the two dates :
int year1 = Integer.parseInt(spl1[0]);
int month1 = Integer.parseInt(spl1[1]);
int days1 = Integer.parseInt(spl1[2]);
int year2 = Integer.parseInt(spl2[0]);
int month2 = Integer.parseInt(spl2[1]);
int days2 = Integer.parseInt(spl2[2]);
//make some calculation and in the end you can get the diffidence, this work i will let it for you.
This should solve your problem.
SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd");
List<Date> dateList = new ArrayList<Date>();
try {
beforeDate = myDateFormat.parse("2016-01-13");
dateList.add(myDateFormat.parse("2016-01-10"));
dateList.add(myDateFormat.parse("2016-01-11"));
dateList.add(myDateFormat.parse("2016-01-12"));
dateList.add(myDateFormat.parse("2016-01-19"));
dateList.add(myDateFormat.parse("2016-01-20"));
dateList.add(myDateFormat.parse("2016-01-21"));
} catch (ParseException e) {
System.out.println(e.getMessage());
}
//add here
boolean check = true;
for(int i = 0; check && i < dateList.size();i++){
if(dateList.get(i).after(beforeDate)){
afterDate = dateList.get(i);
check = false;
}
}
System.out.println(beforeDate+" "+afterDate);
long days = ChronoUnit.DAYS.between(LocalDate.parse(myDateFormat.format(beforeDate)), LocalDate.parse(myDateFormat.format(afterDate)));
if(days>0){
System.out.println(days);
}else{
System.out.println(0-days);
}
if you want to sort dateList then want to get afterDate then use this code after addition of date elements in dateList
Collections.sort(dateList,new Comparator<Date>() {
#Override
public int compare(Date o1, Date o2) {
return o1.compareTo(o2);
}
});
This will allow you to sort dates in ascending order..

Generate a random LocalDate with java.time

I'm writing some code to populate a MySQL database with random data for testing purposes. I need to populate a DATE column with random dates from 1970-2015.
Here's the relevant method:
public Date dateGenerator() throws Exception {
Random ry = new Random();
Random rm = new Random();
Random rd = new Random();
int year = 1969 + ry.nextInt(2015-1969+1);
int month = 1 + rm.nextInt(12);
int day = 1 + rm.nextInt(31);
if (month==2 && day>28){
day = day - 3;
} else {
if((month%2==0 && month != 8 ) && day==31 ){
day = day -1;
}
}
}
My purpose is to create three random integers (for day, month, year) and somehow combine them into some Date object to pass to the database. But the database rejects everything I try to feed it.
It would be very educational for me if you can supply me with a suggestion based in the newest java.time library if this is possible.
A simple way is to convert the minimum and maximum date to their corresponding epoch day, generate a random integer between those two values and finally convert it back to a LocalDate. The epoch day is obtained with toEpochDay() which is the count of days since 1970-01-01 (ISO).
The problem with generating a random year, then month and then day is that you have a small chance of falling with an invalid date (like 31st of February). Also, taking a random epoch day guarantees a uniform distribution across all possible dates.
public static void main(String... args) {
long minDay = LocalDate.of(1970, 1, 1).toEpochDay();
long maxDay = LocalDate.of(2015, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
System.out.println(randomDate);
}
Note that since the minimum date is actually the very first, you could replace it with 0.
To convert this LocalDate into a java.sql.Date, you can refer to this post:
java.sql.Date date = java.sql.Date.valueOf(randomDate);
Try something like this.
public static void main(String[] args) {
LocalDate start = LocalDate.of(1970, Month.JANUARY, 1);
long days = ChronoUnit.DAYS.between(start, LocalDate.now());
LocalDate randomDate = start.plusDays(new Random().nextInt((int) days + 1));
System.out.println(randomDate);
}

Get difference between two dates in years - without months - without days

I am using the following function in Joda-Time to get difference between two dates:
public static int getDiffYear(Date first) {
int yearsBetween = Years.yearsBetween(new DateTime(first), new DateTime()).getYears();
return yearsBetween;
}
The date supplied to function is: 0001-10-02 (YYYY-MM_DD)
I get the difference as 2013 as checked against today, however I find the correct result should be 2012. Because the day still is 01.
I have a separate function in pure Java, with the desired result:
public static int getDiffYear(Date first) {
Calendar a = Calendar.getInstance();
a.setTime(first);
Calendar b = Calendar.getInstance();
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) ||
(a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
diff--;
}
return diff;
}
Joda will take days into account with yearsBetween. Try this:
public static int getDiffYear() {
LocalDate firstDate = new LocalDate(1, 10, 2);
LocalDate today = new LocalDate();
int yearsBetween = Years.yearsBetween(firstDate, today).getYears();
return yearsBetween;
}
It will return 2012 as of today (2014/10/01). This indicates something is happening in the conversion from java.util.Date.
EDIT: This is due to what Marko Topolnik mentioned. When you do new DateTime(first) you are getting a DateTime of 0001-09-30.
The Years utility class is going to only check the difference in years. If you need to keep the days into account, you should use the Days class and recalculate the result to years.

Analog of ORACLE function MONTHS_BETWEEN in Java

Does Java have some analog of Oracle's function MONTHS_BETWEEN?
I've run into the same need and started from #alain.janinm answer which is good but doesn't give the exact same result in some cases.
ex :
Consider months between 17/02/2013 and 11/03/2016 ("dd/MM/yyyy")
Oracle result : 36,8064516129032
Java method from #Alain.janinm answer : 36.74193548387097
Here's the changes i made, to get a closer result to Oracle's months_between() function :
public static double monthsBetween(Date startDate, Date endDate){
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
int startDayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int startMonth = cal.get(Calendar.MONTH);
int startYear = cal.get(Calendar.YEAR);
cal.setTime(endDate);
int endDayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int endMonth = cal.get(Calendar.MONTH);
int endYear = cal.get(Calendar.YEAR);
int diffMonths = endMonth - startMonth;
int diffYears = endYear - startYear;
int diffDays = endDayOfMonth - startDayOfMonth;
return (diffYears * 12) + diffMonths + diffDays/31.0;
}
With this function the result of the call for the dates 17/02/2013 and 11/03/2016 is : 36.806451612903224
Note : From my understanding Oracle's months_between() function considers that all months are 31 days long
You can do that with :
public static int monthsBetween(Date minuend, Date subtrahend){
Calendar cal = Calendar.getInstance();
cal.setTime(minuend);
int minuendMonth = cal.get(Calendar.MONTH);
int minuendYear = cal.get(Calendar.YEAR);
cal.setTime(subtrahend);
int subtrahendMonth = cal.get(Calendar.MONTH);
int subtrahendYear = cal.get(Calendar.YEAR);
return ((minuendYear - subtrahendYear) * (cal.getMaximum(Calendar.MONTH)+1)) +
(minuendMonth - subtrahendMonth);
}
Edit :
According to this documentation MONTHS_BETWEEN return a fractional result, I think this method do the same :
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("02/02/1995");
Date d2 = sdf.parse("01/01/1995");
System.out.println(monthsBetween(d, d2));
}
public static double monthsBetween(Date baseDate, Date dateToSubstract){
Calendar cal = Calendar.getInstance();
cal.setTime(baseDate);
int baseDayOfYear = cal.get(Calendar.DAY_OF_YEAR);
int baseMonth = cal.get(Calendar.MONTH);
int baseYear = cal.get(Calendar.YEAR);
cal.setTime(dateToSubstract);
int subDayOfYear = cal.get(Calendar.DAY_OF_YEAR);
int subMonth = cal.get(Calendar.MONTH);
int subYear = cal.get(Calendar.YEAR);
//int fullMonth = ((baseYear - subYear) * (cal.getMaximum(Calendar.MONTH)+1)) +
//(baseMonth - subMonth);
//System.out.println(fullMonth);
return ((baseYear - subYear) * (cal.getMaximum(Calendar.MONTH)+1)) +
(baseDayOfYear-subDayOfYear)/31.0;
}
I had to migrate some Oracle code to java and haven't found the analog for months_between oracle function. While testing listed examples found some cases when they produce wrong results.
So, created my own function. Created 1600+ tests comparing results of db vs my function, including dates with time component - all work fine.
Hope, this can help someone.
public static double oracle_months_between(Timestamp endDate,Timestamp startDate) {
//MONTHS_BETWEEN returns number of months between dates date1 and date2.
// If date1 is later than date2, then the result is positive.
// If date1 is earlier than date2, then the result is negative.
// If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer.
// Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String endDateString = sdf.format(endDate), startDateString = sdf.format(startDate);
int startDateYear = Integer.parseInt(startDateString.substring(0,4)), startDateMonth = Integer.parseInt(startDateString.substring(5,7)), startDateDay = Integer.parseInt(startDateString.substring(8,10));
int endDateYear = Integer.parseInt(endDateString.substring(0,4)), endDateMonth = Integer.parseInt(endDateString.substring(5,7)), endDateDay = Integer.parseInt(endDateString.substring(8,10));
boolean endDateLDM = is_last_day(endDate), startDateLDM = is_last_day(startDate);
int diffMonths = -startDateYear*12 - startDateMonth + endDateYear * 12 + endDateMonth;
if (endDateLDM && startDateLDM || extract_day(startDate) == extract_day(endDate)){
// If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer.
return (double)(diffMonths);
}
double diffDays = (endDateDay - startDateDay)/31.;
Timestamp dStart = Timestamp.valueOf("1970-01-01 " + startDateString.substring(11)), dEnd = Timestamp.valueOf("1970-01-01 " + endDateString.substring(11));
return diffMonths + diffDays + (dEnd.getTime()-dStart.getTime())/1000./3600./24./31.;
}
public static boolean is_last_day(Timestamp ts){
Calendar calendar = Calendar.getInstance();
calendar.setTime(ts);
int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return max == Integer.parseInt((new SimpleDateFormat("dd").format(ts)));
}
Actually, I think the correct implementation is this one:
public static BigDecimal monthsBetween(final Date start, final Date end, final ZoneId zone, final int scale ) {
final BigDecimal no31 = new BigDecimal(31);
final LocalDate ldStart = start.toInstant().atZone(zone).toLocalDate();
final LocalDate ldEnd = end.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
final int endDay = ldEnd.getDayOfMonth();
final int endMonth = ldEnd.getMonthValue();
final int endYear = ldEnd.getYear();
final int lastDayOfEndMonth = ldEnd.lengthOfMonth();
final int startDay = ldStart.getDayOfMonth();
final int startMonth = ldStart.getMonthValue();
final int startYear = ldStart.getYear();
final int lastDayOfStartMonth = ldStart.lengthOfMonth();
final BigDecimal diffInMonths = new BigDecimal((endYear - startYear)*12+(endMonth-startMonth));
final BigDecimal fraction;
if(endDay==startDay || (endDay==lastDayOfEndMonth && startDay==lastDayOfStartMonth)) {
fraction = BigDecimal.ZERO;
}
else {
fraction = BigDecimal.valueOf(endDay-startDay).divide(no31, scale, BigDecimal.ROUND_HALF_UP);
}
return diffInMonths.add(fraction);
}
public static BigDecimal monthsBetween(final Date start, final Date end) {
return monthsBetween(start, end, ZoneId.systemDefault(), 20);
}
In Joda Time there is a monthsBetween in the org.joda.time.Months class.
I've the same problem and following the Oracle MONTHS_BETWEEN I have made some changes to #alain.janinm and #Guerneen4 answers in order to correct some cases:
Consider months between 31/07/1998 and 30/09/2013 ("dd/MM/yyyy") Oracle result : 182 Java method from #Guerneen4 answer : 181.96774193548387
The problem is that according to specification if date1 and date2 are both last days of months, then the result is always an integer.
For easy understanding here you can find Oracle MONTHS_BETWEEN specifications: https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions089.htm. I copy here to summarize:
"returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2."
Here's the changes that I've done get the closest result to the Oracle's months_between() function :
public static double monthsBetween(Date startDate, Date endDate) {
Calendar calSD = Calendar.getInstance();
Calendar calED = Calendar.getInstance();
calSD.setTime(startDate);
int startDayOfMonth = calSD.get(Calendar.DAY_OF_MONTH);
int startMonth = calSD.get(Calendar.MONTH);
int startYear = calSD.get(Calendar.YEAR);
calED.setTime(endDate);
int endDayOfMonth = calED.get(Calendar.DAY_OF_MONTH);
int endMonth = calED.get(Calendar.MONTH);
int endYear = calED.get(Calendar.YEAR);
int diffMonths = endMonth - startMonth;
int diffYears = endYear - startYear;
int diffDays = calSD.getActualMaximum(Calendar.DAY_OF_MONTH) == startDayOfMonth
&& calED.getActualMaximum(Calendar.DAY_OF_MONTH) == endDayOfMonth ? 0 : endDayOfMonth - startDayOfMonth;
return (diffYears * 12) + diffMonths + diffDays / 31.0;
}
java.time
The other Answers use the troublesome old Calendar class that is now legacy, supplanted by the java.time classes.
MONTHS_BETWEEN
The doc says:
MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Retrieve a LocalDate from the database using JDBC 4.2 and later. The java.sql.Date class is now legacy, and can be avoided.
LocalDate start = myResultSet.getObject( … , LocalDate.class ) ; // Retrieve a `LocalDate` from database using JDBC 4.2 and later.
For our demo here, let’s simulate those retrieved dates.
LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 );
LocalDate stop = start.plusDays( 101 );
Period
Calculate the elapsed time as a span of time unattached to the timeline, a Period.
Period p = Period.between( start , stop );
Extract the total number of months.
long months = p.toTotalMonths() ;
Extract the number of days part, the days remaining after calculating the months.
int days = p.getDays() ;
BigDecimal
For accuracy, use BigDecimal. The double and Double types use floating-point technology, trading away accuracy for fast execution performance.
Convert our values from primitives to BigDecimal.
BigDecimal bdDays = new BigDecimal( days );
BigDecimal bdMaximumDaysInMonth = new BigDecimal( 31 );
Divide to get our fractional month. The MathContext provides a limit to resolving the fractional number, plus a rounding mode to get there. Here we use the constant MathContext.DECIMAL32, because I am guessing the Oracle function is using 32-bit math. The rounding mode is RoundingMode.HALF_EVEN, the default specified by IEEE 754, and also known as “Banker’s rounding” which is more mathematically fair than “schoolhouse rounding” commonly taught to children.
BigDecimal fractionalMonth = bdDays.divide( bdMaximumDaysInMonth , MathContext.DECIMAL32 );
Add this fraction to our number of whole months, for a complete result.
BigDecimal bd = new BigDecimal( months ).add( fractionalMonth );
To more closely emulate the behavior of the Oracle function, you may want to convert to a double.
double d = bd.round( MathContext.DECIMAL32 ).doubleValue();
Oracle did not document the gory details of their calculation. So you may need to do some trial-and-error experimentation to see if this code has results in line with your Oracle function.
Dump to console.
System.out.println( "From: " + start + " to: " + stop + " = " + bd + " months, using BigDecimal. As a double: " + d );
See this code run live at IdeOne.com.
From: 2018-01-23 to: 2018-05-04 = 3.3548387 months, using BigDecimal. As a double: 3.354839
Caveat: While I answered the Question as asked, I must remark: Tracking elapsed time as a fraction as seen here is unwise. Instead use the java.time classes Period and Duration. For textual representation, use the standard ISO 8601 format: PnYnMnDTnHnMnS. For example, the Period seen in our example above: P3M11D for three months and eleven days.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The previous answers are not perfect because they do not handle dates such as Feb 31.
Here is my iterative interpretation of MONTHS_BETWEEN in Javascript...
// Replica of the Oracle function MONTHS_BETWEEN where it calculates based on 31-day months
var MONTHS_BETWEEN = function(d1, d2) {
// Don't even try to calculate if it's the same day
if (d1.getTicks() === d2.getTicks()) return 0;
var totalDays = 0;
var earlyDte = (d1 < d2 ? d1 : d2); // Put the earlier date in here
var laterDate = (d1 > d2 ? d1 : d2); // Put the later date in here
// We'll need to compare dates using string manipulation because dates such as
// February 31 will not parse correctly with the native date object
var earlyDteStr = [(earlyDte.getMonth() + 1), earlyDte.getDate(), earlyDte.getFullYear()];
// Go in day-by-day increments, treating every month as having 31 days
while (earlyDteStr[2] < laterDate.getFullYear() ||
earlyDteStr[2] == laterDate.getFullYear() && earlyDteStr[0] < (laterDate.getMonth() + 1) ||
earlyDteStr[2] == laterDate.getFullYear() && earlyDteStr[0] == (laterDate.getMonth() + 1) && earlyDteStr[1] < laterDate.getDate()) {
if (earlyDteStr[1] + 1 < 32) {
earlyDteStr[1] += 1; // Increment the day
} else {
// If we got to this clause, then we need to carry over a month
if (earlyDteStr[0] + 1 < 13) {
earlyDteStr[0] += 1; // Increment the month
} else {
// If we got to this clause, then we need to carry over a year
earlyDteStr[2] += 1; // Increment the year
earlyDteStr[0] = 1; // Reset the month
}
earlyDteStr[1] = 1; // Reset the day
}
totalDays += 1; // Add to our running sum of days for this iteration
}
return (totalDays / 31.0);
};

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.
So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not important to me).
If you can use Joda, this is super simple:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Of course you could combine these.
int days = Days.daysBetween(startDate, endDate).getDays();
Joda objects can go back and forth between the JDK's date class pretty easily.
For the first part, make a DateFormatter then parse the string based on it, like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
(After turning the int into a string of course.)
Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?
public static long numberOfDays(final long date) throws ParseException {
final Calendar compare = Calendar.getInstance();
compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
final int dstOffset = compare.get(Calendar.DST_OFFSET);
final long currentTimeMillis = System.currentTimeMillis();
final long compareTimeInMillis = compare.getTimeInMillis();
long difference = 0;
if (currentTimeMillis >= compareTimeInMillis) {
difference = currentTimeMillis - compareTimeInMillis - dstOffset;
} else {
difference = compareTimeInMillis - currentTimeMillis + dstOffset;
}
return difference / (24 * 60 * 60 * 1000);
}
Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

Categories