如何计算剩余天数?

时间:2015-07-20 17:38:03

标签: java android android-studio

private long calculateRemainingDays() {


        final Calendar c = Calendar.getInstance();
        c.set(2015, 7, 23);
        final Calendar today = Calendar.getInstance();

        final long millis = c.getTimeInMillis()
                - today.getTimeInMillis();
        // Convert to days
        final long days = millis / 86400000;
        return days;
}

我需要在我的android应用程序中添加一个函数。我希望从当天到2015/9/30剩余的几天。当日期更改为第二天时,剩余天数将减少。我想这样说: 剩下7天... 6/5/4 /等等......请帮我正确的剩余天数。抱歉我的英语不好。谢谢!

3 个答案:

答案 0 :(得分:2)

Calender.JULY方法的参数中使用7代替set()

7 = August. 6 = July.

因为January0开头。最好使用静态实例变量,如Calender.JANUARY

但是,如果要计算到2015/9/30,则应将值设置为

c.set(2015, Calender.SEPTEMBER, 09);

其余代码似乎没问题。它将返回正确的天数。

答案 1 :(得分:0)

如果您不介意使用joda.time

你可以做这种形式的事情:

final Calendar c = Calendar.getInstance();
c.set(2015, Calender.SEPTEMBER, 30);
Date endDate = c.getTime();
Instant startInstant = new Instant(new Date());
Instant endInstant = new Instant(endDate);
Days days = Days.daysBetween(startInstant, endInstant);

答案 2 :(得分:0)

试试这个: -

final long millis = c.getTimeInMillis()
                - today.getTimeInMillis();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(millis , TimeUnit.MILLISECONDS));