0

我有一个日期:21/08/2013 17:05:06 我想知道 22/08/2013 00:00:00 之前的毫秒数

请问可以用 Calendar 对象做到这一点吗?谢谢

编辑 :

我的解决方案发现:

Calendar cal2 = Calendar.getInstance(TimeZone.getDefault());
                cal2.setTimeInMillis(prevCalBatt.getTimeInMillis());
                cal2.add(Calendar.DAY_OF_MONTH,1); //add a day
                cal2.set(Calendar.HOUR_OF_DAY, 0); //set time to midnight
                cal2.set(Calendar.MINUTE, 0);
                cal2.set(Calendar.SECOND, 0);
                cal2.set(Calendar.MILLISECOND, 0);

                timeBetweenBoth+=(cal2.getTimeInMillis()-prevCalBatt.getTimeInMillis());
4

3 回答 3

1

为每个日期创建一个日历对象,然后减去它们的getTimeInMillis().

于 2013-08-21T15:10:00.123 回答
0
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

GregorianCalendar cal = new GregorianCalendar();

cal.setTime(sdf.parse("22/08/2013 00:00:00"));

long millis = cal.getTimeInMillis();

cal.setTime(sdf.parse("21/08/2013 17:05:06"));

millis -= cal.getTimeInMillis();
于 2013-08-21T15:24:52.510 回答
0

您可以使用以下方法设置闹钟:

/**
     * Set the Alarm
     *
     * @param context  the activity context
     * @param id       the alarm ID for this app
     * @param hour     the alarm hour
     * @param minute   the alarm minute
     * @param timeZone the timezone "am" = Calendar.AM or "pm" = Calendar.PM
     */
    public static void setAlarm(Context context, int id, int hour, int minute, String timeZone) {
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        AlarmStateCache cache = AlarmStateCache.getInstance(context);
        cache.saveState(State.ON);

        Calendar now = Calendar.getInstance();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, to24Hour(hour, timeZone));
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);

        if(calendar.before(now))
            calendar.add(Calendar.DAY_OF_MONTH,1);

        Intent intent = new Intent(context, YourReceiver.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(context, id, intent, 0);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 20, pIntent);
    }

和辅助方法

   public static int to24Hour(int hour, String zone) {
        if (1 > hour && hour < 12)
            throw new IllegalArgumentException("Hour must only be 1 - 12!");

        return zone.equals("am") ? hour : hour + 12;
    }

setAlarm方法中我们可以看到如果我们当前的时间已经过去,我们会增加 1 天,因此我们可以确保时间会在第二天左右提示。

于 2015-07-09T07:55:34.487 回答