JAVA小練習:求兩個日期的差值

kisslfcr發表於2017-12-28

點選(此處)摺疊或開啟

  1. import java.util.Scanner;
  2. class fundemo6{
  3. public static void main(String[] arg){
  4.     Scanner s=new Scanner(System.in);
  5.     System.out.println("Please input first date year:");
  6.     int y1=s.nextInt();
  7.     System.out.println("Please input first date month:");
  8.     int m1=s.nextInt();    
  9.     System.out.println("Please input first date day:");
  10.     int d1=s.nextInt();    
  11.     System.out.println("The first date you input is:"+y1+"-"+m1+"-"+d1);
  12.     System.out.println("Please input second date year:");
  13.     int y2=s.nextInt();
  14.     System.out.println("Please input second date month:");
  15.     int m2=s.nextInt();    
  16.     System.out.println("Please input second date day:");
  17.     int d2=s.nextInt();    
  18.     System.out.println("The second date you input is:"+y2+"-"+m2+"-"+d2);
  19.     System.out.println("sub days of two years is:"+subDays(y1,m1,d1,y2,m2,d2));
  20.     }
  21. public static int getDays(int y,int m,int d){
  22.     int sum=0;
  23.     switch(m-1){
  24.     case 11:sum+=30;
  25.     case 10:sum+=31;
  26.     case 9:sum+=30;
  27.     case 8:sum+=31;
  28.     case 7:sum+=31;
  29.     case 6:sum+=30;
  30.     case 5:sum+=31;
  31.     case 4:sum+=30;
  32.     case 3:sum+=31;
  33.     case 2:if(isLeap(y))
  34.                 sum+=29;
  35.                 else
  36.                 sum+=28;
  37.     case 1:sum+=31;
  38.     }
  39.     sum+=d;
  40.     return sum;
  41.     }
  42. public static boolean isLeap(int y){
  43.     if(y%100!=0&&y%4==0||y%400==0)
  44.         return true;
  45.         return false;
  46. }
  47. public static int otherDays(int y,int m,int d){
  48.     if(isLeap(y))
  49.     return 366-getDays(y,m,d);
  50.     return 365-getDays(y,m,d);
  51. }
  52. public static int subDays(int y1,int m1,int d1,int y2,int m2,int d2){
  53.     if(y1==y1)
  54.         int day1=getDays(y1,m1,d1)-getDays(y2,m2,d2);
  55.     return abs(day1);
  56. }
  57. public static int abs(int n){
  58.     return n>=0?n:-n;
  59. }
  60. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29135257/viewspace-2149455/,如需轉載,請註明出處,否則將追究法律責任。

相關文章