Note that there are some explanatory texts on larger screens.

plurals
  1. PODays between 2 given dates
    text
    copied!<p>I have been given a task to calculate the number of days between 2 given dates and have found a really strange result (2127 days) for Input Line 3 which seems to be correct but the given output expected for this task is a different result (1979 days). I've looked at this post <a href="https://stackoverflow.com/questions/7103064/calculate-the-number-of-days-between-two-dates">Calculate the number of days between two dates</a> along with several other posts on here and used the Joda library as advised and get a result of 2127 days.</p> <p>*Problem: Given two dates (during the years 1901 and 2999, inclusive), find the number of days between the two dates.</p> <p>Input: Six sets of data. Each set has two dates in the format month, day, year. For example, the input line '6, 2, 1983, 6, 22, 1983' represents June 2, 1983 to June 22, 1983.</p> <p>Output: The number of days between the given dates, excluding the starting date and the ending date. For example, there are 19 days between June 2, 1983 and June 22, 1983; namely, June 3, 4, ..., 21.</p> <p>Sample Input (3 sets):</p> <pre><code> Input Line #1: 6, 2, 1983, 6, 22, 1983 Output #1: 19 Input Line #2: 7, 4, 1984, 12, 25, 1984 Output #2: 173 Input Line #3: 1, 3, 1989, 3, 8, 1983 Output #3: 1979 </code></pre> <p>Here is my solution </p> <pre><code>private boolean isYearValid(int year){ return year &gt;=1901 &amp;&amp; year &lt;= 2999; } public int numOfDays(String dates){ Calendar date1 = new GregorianCalendar(); Calendar date2 = new GregorianCalendar(); String [] dateSplit = dates.split(","); int len = dateSplit.length; int year = 0; for(int i=0;i&lt;len;i++){ dateSplit[i]=dateSplit[i].trim(); if(i==2||i==5){ try { year = Integer.parseInt(dateSplit[i]); } catch (NumberFormatException e){ throw new IllegalArgumentException(String.format("Usage: Year input %s is not valid",dateSplit[i])); } if(!isYearValid(year)) throw new IllegalArgumentException("Usage: Year of date should be between the years 1901 and 2999, inclusive"); } } int [] d = new int[6]; for(int i=0;i&lt;6;i++) try { d[i]=Integer.parseInt(dateSplit[i]); } catch(NumberFormatException e){ throw new IllegalArgumentException("Usage: Date entered is not valid"); } date1.set(d[2], d[0],d[1]); date2.set(d[5], d[3], d[4]); long milli1= date1.getTimeInMillis(); long milli2 = date2.getTimeInMillis(); long diff; if(milli1&gt;milli2){ diff = milli1 - milli2; } else{ diff = milli2 - milli1; } return (int) (diff / (24 * 60 * 60 * 1000))-1; } </code></pre> <p>Solved - Seems like the test data was wrong since <code>1, 3, 1989, 8, 3, 1983</code> produces 1979 days.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload