2

I know there are a lot of similar questions, but none of them specifically solved my issue, it's an uni project and we are not allowed to use advanced/external stuff.

So basically the purpose is to calculate if the product which was rent and its being returned, has expired the time limit X the client can keep it, and if the expected return date it's a saturday or sunday, it should jump to the next monday (I can probably manage this simple logic).

public void newRent(Client client, Product product){
    SomeDateFormat rentDate = SomeDateFormat.today();
    SomeDateFormat expectedReturnDate;
}

...

public void returnProduct(Client client, Product product){
    int diffDays = SomeDateFormat.today() - product.getRentDay();
}
Mojimi
  • 2,561
  • 9
  • 52
  • 116
  • Check [Java, Calculate the number of days between two dates](http://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates). – MChaker May 17 '15 at 17:56

3 Answers3

4

You could try this:

SimpleDateFormat testDate = new SimpleDateFormat("dd MM yyyy");
String timeString1 = "01 01 1990";
String timeString2 = "30 05 1990";

    Date dateTime1 = myFormat.parse(timeString1 );
    Date dateTime2 = myFormat.parse(timeString2 );
    long diff = dateTime2.getTime() - dateTime1.getTime();
    System.out.println ("Days between: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
hamena314
  • 2,969
  • 5
  • 30
  • 57
  • This line "long diff = dateTime2.getTime() - dateTime1.getTime();" is giving me a binary operator error – Mojimi May 18 '15 at 00:54
2

You may use the following code snippet -

long diffDays = date1.getTime() - date2.getTime();
return TimeUnit.DAYS.convert(diffDays, TimeUnit.MILLISECONDS);  

Here, date1 and date2 are of type Date.

Razib
  • 10,965
  • 11
  • 53
  • 80
  • This code isn't working correctly. If `date1` is tomorrow and `date2` is "now", then the result is **0**. Your code can't handle dates with a certain amount of time. – Tom May 17 '15 at 18:03
1

This should work;

public long getDays(Date get, Date ret) {

    Calendar cal = Calendar.getInstance();
    cal.setTime(ret);

    //Monday stuff here
    int day = cal.get(java.util.Calendar.DAY_OF_WEEK);
    if (day == 1) {
        cal.add(Calendar.DATE, 1);
    } else if (day == 7) {
        cal.add(Calendar.DATE, 2);
    }

    ret = cal.getTime();

    long diff = ret.getTime() - get.getTime();
    return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
dogant
  • 1,376
  • 1
  • 10
  • 23