如何计算到设定时间的剩余时间

How to calculate remaining hours to setted time

我想在 Android(Java) 中创建类似闹钟的应用程序,我想计算剩余的小时数和分钟数。当我将闹钟设置为 1:00 am 时。我现在的时间是 20:00 下午,它会告诉我 "Alarm will sound after 5 hours",但它会在 19 小时后告诉我如何解决它。

Toast.makeText(this, "Hours: " + (calendar.getTime().getHours() - timePicker.getCurrentHour()) + "Minutes: " + (calendar.getTime().getMinutes() - timePicker.getCurrentMinute()) , Toast.LENGTH_SHORT).show();

你应该使用 Java 日期。

Calendar cal = Calendar.getInstance().set(...); //set the date
Date alarmDate = cal.time;

long duration = alarmDate - System.currentTimeMillis();
int hours = duration / (1000 * 60 * 60);

java.time

现代解决方案使用 java.time 类。

获取默认时区的当前时刻。如果重要,请与用户确认。

ZoneId z = ZoneId.systemDefault() ; 
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

提取时间。

LocalTime lt = zdt.toLocalTime() ;

如果在闹钟时间之后,加一天。

LocalTime alarm = LocalTime.of( 1 , 0 ) ;

LocalDate ld = zdt.toLocalDate() ;
if( ! alarm.isBefore( lt ) ) {
    ld = ld.plusDays( 1 ) ;
}

ZonedDateTime fire = ZonedDateTime.of( ld , alarm , z ) 

如果您的其他代码需要 UTC,请提取 Instant

Instant instant = fire.toInstant() ;

计算经过的时间。

Duration d = Duration.between( zdt , fire ) ; 
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;

您应该添加更多代码,一个软糖因素,以防当前时刻非常接近警报时间,足够接近以至于它可能会在执行此代码时翻转警报时间。


关于java.time

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.

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

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?

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.

尝试这样的事情:

    Calendar cal = Calendar.getInstance();

    int hrs = cal.get(Calendar.HOUR_OF_DAY);

    Calendar alCal = Calendar.getInstance();
    alCal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());

    alCal.set(Calendar.MINUTE, timePicker.getCurrentMinute());

    if(timePicker.getCurrentHour() < hrs){
        alCal.add(Calendar.DAY_OF_MONTH, 1);
    }

    long diff = alCal.getTimeInMillis() - cal.getTimeInMillis();

    long leftHrs = (diff / (60 * 60 * 1000));
    long leftMin = (diff / (60 * 1000)) - (leftHrs * 60);

    // Output
    Toast.makeText(this,"Hours: "+leftHrs+"Minutes: "+leftMin,Toast.LENGTH_SHORT).show();