大部分人选用截取年月日字符串,转整型,然后判断闰年,二月有多少天来计数。
本文尝试使用Date获取相对1970年1月1日相差得毫秒数计算
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String str=in.next();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy,MM,dd");//设置格式
try {//输入异常捕获
Date date=sdf.parse(str);
long now = date.getTime()/1000/60/60/24;//获取1970年1月1日到指定是时间的毫秒数计算得天数
Date date1=sdf.parse(str.substring(0,4)+",01,01");//设置时间为该年的第一天
long before = date1.getTime()/1000/60/60/24;//获取1970年1月1日到指定是该年的第一天的天数
System.out.println("今年的第"+(now-before+1)+"天");//计算加一,默认1月1日为第一天
} catch (ParseException e) {
e.printStackTrace();
}
}
使用date方法直接得出结果
public class CalculateDayOfYear {
public static void main(String[] args) {
int year = 2023; int month = 9;
int day = 3; // 创建LocalDate对象
LocalDate date = LocalDate.of(year, month, day); // 获取这一年的第几天
int dayOfYear = date.getDayOfYear();
System.out.println("这一天是这一年的第" + dayOfYear + "天");
}
}