Set the Calendar to a specific date?

2019-07-07 00:06发布

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.

4条回答
冷血范
2楼-- · 2019-07-07 00:51

tl;dr

ZonedDateTime.of(
    LocalDate.of( 2015 , Month.JANUARY , 8 ) ,
    LocalTime.of( 7 , 13 , 0 ) ,
    ZoneId.of( "Africa/Tunis" ) 
)
.toInstant()
.toEpochMilli()

1420697580000

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes. So much easier and cleaner now.

Your code is ambiguous, as you do not address the crucial issue of time zone. As you did not specify a time zone explicitly, your JVM’s current default time zone will be applied implicitly. I strongly recommend always specifying your desired/expected time zone.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

LocalDate ld = LocalDate.of( 2015 , Month.JANUARY , 8 ) ;
LocalTime lt = LocalTime.of( 7 , 13 , 0 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

You could use a combo factor method, alternatively.

ZonedDateTime zdt = ZonedDateTime.of( 2015 , Month.JANUARY , 8 , 7 , 13 , 0 , 0 , ZoneId.of( "Pacific/Auckland" ) ) ;

I generally recommend against tracking date-time as a count-from-epoch. But it seems to be requirement in your case.

First we can extract a Instant, a moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;  // Convert from a zoned value to a UTC value.

You can then ask for the count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z. Beware of possible data loss, as any microseconds or nanoseconds in the Instant will be ignored when reporting mere milliseconds.

long millis = instant.toEpochMilli() ;  // Count of milliseconds since 1970-01-01T00:00:00Z.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-07 01:04

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
查看更多
迷人小祖宗
4楼-- · 2019-07-07 01:06

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 );
查看更多
等我变得足够好
5楼-- · 2019-07-07 01:11

To add an hour by example, you can do something like this :

calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 1);
查看更多
登录 后发表回答