Java 案例十三 出生的到現在的天數 潤年的求法(不一樣的演算法)
阿新 • • 發佈:2019-01-14
高階的演算法:
日曆設定到指定年份的3月1日,add向前偏移1天,獲取天數,29潤年
package cn.demo04; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Scanner; public class DateTest { public static void main(String[] args) throws Exception { function(); function_1(); } /* * 潤年計算 * 2000 3000 * 高階的演算法: * 日曆設定到指定年份的3月1日,add向前偏移1天,獲取天數,29潤年 */ public static void function_1(){ Calendar c = Calendar.getInstance(); //將日曆,設定到指定年的3月1日 c.set(2000, 2,1); //日曆add方法,向前偏移1天 c.add(Calendar.DAY_OF_MONTH, -1); //get方法獲取天數 int day = c.get(Calendar.DAY_OF_MONTH); System.out.println(day); } /* * 計算活了多少天 * 生日 今天的日期 * 兩個日期變成毫秒值,減法 */ public static void function() throws Exception{ System.out.println("請輸入生日日期 格式:yyyy-MM-dd"); //獲取出生日期,鍵盤輸入 String birthdayString = new Scanner(System.in).next(); //將字串日期,轉成date物件 //建立SimpleDateFormat物件,寫日期模式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //呼叫方法parse,字串轉變成日期物件 Date birthdayDate = sdf.parse(birthdayString); //獲取今天的日期 Date toDayDate = new Date(); //將兩個日期轉成毫秒值,Date類的方法getTime long birthdaySecond = birthdayDate.getTime(); long todaySecond = toDayDate.getTime(); long second = todaySecond-birthdaySecond; if(second < 0){ System.out.println("還沒有出生"); }else{ System.out.println(second/1000/60/60/24); } } }
輸出的結果是: