java實現閏年區分並計算一天在一年中的第幾天
阿新 • • 發佈:2019-01-08
// date為"2018-01-27"形式
public static float getJ(String date){
int year = 0;
int MM = 0;
int dd = 0;
try {
Date sdf = new SimpleDateFormat("yyyy-MM-dd").parse(date);
SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd");
// 擷取年份
String str0 = sdf0.format(sdf);
// 擷取月份
String str1 = sdf1.format(sdf);
// 擷取日
String str2 = sdf2.format(sdf);
// 轉int型別
year = Integer.parseInt(str0);
MM = Integer.parseInt(str1);
dd = Integer.parseInt(str2);
} catch (ParseException e) {
e.printStackTrace();
}
// J ---為儒略日,取值範圍為1到365或366;
int J =0;
for (int i = 1; i < MM; i++) {
J = getJ(year, i, dd);
}
return J;
}
//能被4整除且不能被100整除或者能被400整除的年份為閏年
public static int getJ(int year,int month,int day) {
int totalDay=0;
for(int i=1;i<month;i++){
totalDay+=getMonthDay(year,i);
}
int J = totalDay+day;
return J;
}
public static int getMonthDay(int year,int month){
boolean flag=isRunnian(year);
if(month==2){
if(flag==true){
return 29;
}else{
return 28;
}
}else if(month==4||month==6||month==9||month==11){
return 30;
}else{
return 31;
}
}
public static boolean isRunnian(int year){
if((year%4==0&&year%100!=0)||(year%400==0)){
return true;
}else{
return false;
}
}