Java - 每周重复的日历倒计时

时间:2017-05-28 04:45:01

标签: java calendar reset recurring-events

我正在尝试制作一个倒计时器,每周重置一次(周一上午10点在东部)。我找到了类似于我正在寻找的东西,但它没有重置自己;它进入了负面。有人可以帮我解决这个问题吗?

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();
    }
}    

一旦达到重置时间,我无法弄清楚如何重置。任何帮助非常感谢。我没有5年多的编码。

如果时间过去,下面是输出的屏幕截图。

https://puu.sh/w3odJ/009663b380.png

谢谢!

更新:我发现最好的方法是使用reset.addreset日历添加7天。但是,为了实现这一目标,无法获得满足的适当条件。我已经尝试了reset.compareTo(today)以及其他一些不起作用的组合,但它已经取得了进展。

0 个答案:

没有答案