简体   繁体   中英

Calendar.get(Calendar.DATE) gets wrong value

I have a reminder application in which the user can create one-time reminders and repeatable ones.

When the user selects the one-time reminder, a reminder object is being created and the following code snippet is called in the constructor, the program tries to calculate the exact date it should go off.

But with this I get the DATE component always the next day. Regardless if I set a time that passed for today, or I set a time that hasn't passed for today. What could go wrong with this?

public void calculateExactDate() {
    if (Utils.isReminderOnlyOnce(days)) {
        Calendar now = Calendar.getInstance();
        Calendar reminderDate = Calendar.getInstance();

        reminderDate.set(Calendar.HOUR, hour);
        reminderDate.set(Calendar.MINUTE, minute);
        reminderDate.set(Calendar.SECOND, 0);

        if (now.getTimeInMillis() > reminderDate.getTimeInMillis()) {
            reminderDate.add(Calendar.DATE, 1);
        }

        year = reminderDate.get(Calendar.YEAR);
        month = reminderDate.get(Calendar.MONTH) + 1;
        day = reminderDate.get(Calendar.DATE);
    }
}

Edit: Maybe it's worth to mention that the code that adds a day never runs.

I tried to get the difference if I set the two calendars equal (or at least this is what I thought). The difference was around -43200000 ms which is 12 hours.

I knew it's related to the am/pm or 24 hour problem. And yes, I checked: the Calendar.HOUR field is for the am/pm format, and the Calendar.HOUR_OF_DAY is used for the 24-hour clock.

So instead of HOUR I have to use Calendar. HOUR_OF_DAY constant, and it works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM