Java 中计算一年中剩余的天数


若要获得今年剩余的天数,请找出当前年份总天数与已过去天数的差值。

首先,计算今年的天数。

Calendar calOne = Calendar.getInstance();
int dayOfYear = calOne.get(Calendar.DAY_OF_YEAR);

现在,计算 2018 年当前年份的总天数。

int year = calOne.get(Calendar.YEAR);
Calendar calTwo = new GregorianCalendar(year, 11, 31);
int day = calTwo.get(Calendar.DAY_OF_YEAR);
System.out.println("Days in current year: "+day);

找出天数差,即可获得今年剩余的天数。

以下是完整示例。

示例

 实时示例

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String args[]) {
      Calendar calOne = Calendar.getInstance();
      int dayOfYear = calOne.get(Calendar.DAY_OF_YEAR);
      int year = calOne.get(Calendar.YEAR);
      System.out.println("Current Year: "+year);
      Calendar calTwo = new GregorianCalendar(year, 11, 31);
      int day = calTwo.get(Calendar.DAY_OF_YEAR);
      System.out.println("Days in current year: "+day);
      int total_days = day - dayOfYear;
      System.out.println("Total " + total_days + " days remaining in "+year);
   }
}

输出

Current Year: 2018
Days in current year: 365
Total 38 days remaining in 2018

更新于: 2020 年 6 月 29 日

471 次浏览

启动你的事业

通过完成该课程,获得认证

立即开始
广告