0

I have 2 dates assigned to a Calendar instance. (now, and then).

Calendar currentDate = new Calendar().getInstance();

Calendar oldDate = Calendar.getInstance();
oldDate.setTimeInMillis(plugin.joinTimeLog.getLong(p.getName() + ".time"));

Basically, what I am aiming to achieve is that an event may only occur once per month (every 30 days). If 30 days has not passed, then tell them how long until a month will have passed.

Eg. "21d 17hrs 54mins until you have access."

Here is my current code which seems to give a completely incorrect number of days and hours (note; I have not setup minutes yet).

Calendar timeLeft = Calendar.getInstance();
timeLeft.setTimeInMillis(currentDate.getTimeInMillis() - (oldDate.getTimeInMillis() + (60 * 60 * 24 * 30 * 1000)));
int daysLeft = daysBetween(currentDate, timeLeft);
int hoursLeft = Math.round(hoursBetween(currentDate, timeLeft));

I then use the following code to determine if a month had passed;

if (daysLeft <= 0) {

And here are my methods to obtain the daysLeft and hoursLeft;

public int daysBetween(Calendar d1, Calendar d2) {
    return (int)( (d1.getTimeInMillis() - d2.getTimeInMillis()) / (1000 * 60 * 60 * 24));
}

public int hoursBetween(Calendar d1, Calendar d2) {
    return (int)( (d1.getTimeInMillis() - d2.getTimeInMillis()) / (1000 * 60 * 60));
}
Axiom
  • 37
  • 6
  • You want to get the remaining time in a month? – waltersu Jun 04 '16 at 04:30
  • How long **until** a month **had** passed is contradictory. Can you clarify whether you want to know how long since the previous month finished or how long left until the next month starts. – MikeT Jun 04 '16 at 04:44
  • 1
    Define "1 month". `Feb 14, 2015` to `Mar 15, 2015` is **more than a month**, but only **29 days**. `Mar 15, 2015` to `Apr 14, 2015` is **30 days**, so longer, but **less than a month**. So if you only count days, how long is a month? – Andreas Jun 04 '16 at 04:55
  • @Andreas I have updated the post. – Axiom Jun 04 '16 at 06:18
  • So, take original date (`oldDate`) and add 30 days (`oldDate.add(Calendar.DAY_OF_MONTH, 30)`), that is your target. Calculate milliseconds until target (`millisToGo = oldDate.getTimeInMillis() - System.currentTimeMillis()`). If `<= 0`, you're good to go, otherwise print value as days+hours+minutes. Beware Daylight Savings Time changes. – Andreas Jun 04 '16 at 07:09
  • Also a duplicate of [this](http://stackoverflow.com/q/1770010/642706), [this](http://stackoverflow.com/q/238920/642706), [this](http://stackoverflow.com/q/25186390/642706), [this](http://stackoverflow.com/q/1555262/642706), and many more. – Basil Bourque Jun 04 '16 at 09:02

0 Answers0