Set the Calendar to a specific date?
Solution 1
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
Try using a better date-time library, such as Joda-Time.
In Joda-Time you can change the date while keeping the time of day. Or, vice-versa, keep the time of day while keeping the date.
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) ;
DateTime todayNoon = now.withTime( 12, 0, 0, 0 ) ;
DateTime midMarchSameYearSameTimeAsNow = now.withDate( now.getYear(), DateTimeConstants.MARCH, 15 );
DateTime tomorrowSameTime = now.plusDays( 1 );
Solution 2
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
user1579019
Updated on July 22, 2022Comments
-
user1579019 almost 2 years
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.