鍵盤錄入出生年月日,輸出已經活了的天數

 1 import java.text.ParseException;
 2 import java.text.SimpleDateFormat;
 3 import java.util.Date;
 4 import java.util.Scanner;
 5 
 6 public class DayCount {
 7     public static void main(String[] args) throws ParseException {
 8         Scanner sc = new Scanner(System.in);
 9         System.out.println("請輸入你的出生年月日:");
10         String s=sc.nextLine();
11         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
12         //將String轉換爲Date
13         Date d=sdf.parse(s);
14         //獲得d時的毫秒值
15         long time1=d.getTime();
16         //獲得當前的毫秒值
17         long time2=new Date().getTime();
18         //相減獲得天數
19         System.out.println("你一共活了:"+(time2-time1)/1000/60/60/24+"天");
20     }
21 }

結果顯示:java

 1 請輸入你的出生年月日: 2 1999-05-13 3 你一共活了:7652天 spa

相關文章
相關標籤/搜索