2021-01-03

算日期

输入一个日期,输出这是这一年的第几月的第几周,星期几

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Main {
     
   public static void main(String[] args){
     
	  Scanner in=new Scanner(System.in);
	  String str=in.nextLine();
	  String[] split=str.split(" ");
	  int year=Integer.parseInt(split[0]);
      int monthNumber=Integer.parseInt(split[1]);
	  int weekday=calendar(year,monthNumber);
	  int day=day_of_month(weekday,Integer.parseInt(split[2]),Integer.parseInt(split[3]));
	  if(monthNumber-1==1){
     
		  if(isLeapYear(year)){
     
			  //29day
			  if(day<29){
     
				 System.out.println(year+"  "+monthNumber+"  "+(day+1)); 
			  }
		  }else{
     
			  //28day
			  if(day<28){
     
				  System.out.println(year+"  "+monthNumber+"  "+(day+1)); 
				  
			  }
		  }
	  }else if((monthNumber-1)%2==0 || monthNumber-1==7 || monthNumber-1==9 || monthNumber-1==11){
     
		  //31day
		  if(day<31){
     
			  System.out.println(year+"  "+monthNumber+"  "+(day+1)); 
			  
		  }
	  }else{
     
		  //30day
		  if(day<30){
     
			  System.out.println(year+"  "+monthNumber+"  "+(day+1)); 
			  
		  }
	  }
   }
   public static  int day_of_month(int weekday, int week_of_month, int weekday1){
     
	   int day=0;
	   if(week_of_month>0){
     
		   day=week_of_month*7+weekday1-weekday;
	   }else{
     
		   day=weekday1-weekday;
	   }
	   return day;
   }
   public static  boolean isLeapYear(int year){
     
	   if(year%4==0 && year%100!=0){
     
		 return true;  
	   }
	   return false;
   }
   public static int calendar(int year, int month){
     
	   String[] weekDays = {
      "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	   SimpleDateFormat f=new SimpleDateFormat("yyyy MM dd");
	   Calendar calendar = Calendar.getInstance();
	   Date date;
	try {
     
			date = f.parse("" + year + " " + month + " 01");
			calendar.setTime(date);
	} catch (ParseException e) {
     
		
		e.printStackTrace();
	}
	//一周的第几天
    int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
    if (w < 0)
        w = 0;
    return w;	   
	   
   }
   
}

你可能感兴趣的:(java)