Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the Calendar to a specific date?

I want to set a reminder with notification on a specific date. Then I am using AlarmManager with NotificationManager currently. When I set selected date from dateDialog, the reminder is working. How can I put calendar value on alarm set with fixed time? I get the current date and time from this :

Calendar calendar =  Calendar.getInstance();

and then I can set the calendar manually like below and it's working:

calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 13);
calendar.set(Calendar.HOUR, 7);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 8);
calendar.set(Calendar.YEAR,2015);
long when = calendar.getTimeInMillis();

But my question is how can I set the calendar to tomorrow and 9:00 AM or set the calendar exactly to a particular month (or year) later from the current date? I mean something like this :

calendar.add(Calendar.DAY_OF_MONTH, 1);

but it does not work.

like image 873
user1579019 Avatar asked Jan 08 '15 07:01

user1579019


People also ask

How do you set a specific date in Java?

The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.

How do you initialize a calendar date in Java?

We have to initialize calendar like this: Calendar date = Calendar. getInstance(); date.


1 Answers

For me this works just fine on the desktop, couldn't test it on Android though.
Update: just tested this on my Android phone using AIDE, getting the exact same results.

import java.util.Calendar;

public class CalendarTest {

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();

        System.out.println(calendar.getTimeInMillis() + " -> " + calendar.getTime());

        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 13);
        calendar.set(Calendar.HOUR, 7);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 9);
        calendar.set(Calendar.YEAR, 2015);

        System.out.println(calendar.getTimeInMillis() + " -> " + calendar.getTime());

        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.YEAR, 1);

        System.out.println(calendar.getTimeInMillis() + " -> " + calendar.getTime());
    }

For this test my output is just what you would expect:

1420705649927 -> Thu Jan 08 09:27:29 CET 2015
1420783980927 -> Fri Jan 09 07:13:00 CET 2015
1452406380927 -> Sun Jan 10 07:13:00 CET 2016
like image 66
tringel Avatar answered Oct 10 '22 17:10

tringel