I'm trying to make a countdown timer that will reset weekly (Mondays at 10am eastern). I've found something similar to what I'm looking for, but it doesn't reset itself; it goes into the negative. Can someone please help me get this working?
public static int SECONDS_IN_A_DAY = 24 * 60 * 60;
public String main(String[] args) {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
Calendar reset = Calendar.getInstance();
reset.setTime(new Date(0));
reset.set(Calendar.DAY_OF_WEEK, 1); //2
reset.set(Calendar.MONTH, month);
reset.set(Calendar.YEAR, year);
reset.set(Calendar.HOUR_OF_DAY, 0); //10
reset.set(Calendar.MINUTE, 33);
Calendar today = Calendar.getInstance();
long diff = reset.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600);
if (diff < 0) {
reset.setTime(new Date(0));
reset.set(Calendar.DAY_OF_WEEK, 1); //2
reset.set(Calendar.MONTH, month);
reset.set(Calendar.YEAR, year);
reset.set(Calendar.HOUR_OF_DAY, 0); //10
reset.set(Calendar.MINUTE, 33);
}
return "Reset in: " + days + " days, " + hours + " hours, " + minutes + " minutes, and " + seconds + " seconds.";
}
public void onMessageReceived(MessageReceivedEvent e) {
if(e.getMessage().getRawContent().equalsIgnoreCase(";reset")) {
e.getChannel().sendMessage(main(null)).queue();
}
}
I cant figure out how to make this reset once it reaches reset time. Any help very much appreciated. I haven't coded in 5+ years.
Below is screenshot of the output if the time has passed.
https://puu.sh/w3odJ/009663b380.png
Thanks!
UPDATE: I'm finding the best method for this is to use reset.add
to add 7 days to the reset
calendar. Can't get the proper conditions to be met to achieve this yet though. I've tried reset.compareTo(today)
as well as some other combinations which aren't working, but it's progress.
diff
was negative, which would happen if thereset
date was beforetoday
, then all the other values calculated would be negative, too.