获取 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); 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 current year"); } }
输出
Days in current year: 365 Total 38 days remaining in current year
广告