分別使用Jdk8和8以前的特性解決一個年齡大小的問題
需求:鍵盤輸入一個年齡浆兰,來求年齡到底有多大型将?
在Jdk8以前的版本中,只能依靠Date()獲得當前時間和基準時間凫岖,這個基準時間就是1970年8:00悦穿,然后利用毫秒數(shù)進行計算蛛株,然后轉(zhuǎn)換為年周霉。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class DateYear{
public static void main(String[] args) throws ParseException {
//鍵盤錄入一個人的生日雨席,例如2000-03-04
Scanner sc=new Scanner(System.in);
System.out.println("請輸入生日");
String birth=sc.nextLine();
//先求輸入值與1970年之間的時間長度
Date date1=new Date(0L);
//這里是進行格式化
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
//將字符串格式化進行解析
Date date2 = simpleDateFormat.parse(birth);
//現(xiàn)在需要的是date2-date1的毫秒數(shù)
long date1Time = date1.getTime();
long date2Time = date2.getTime();
//我們還需要當前時間毫秒數(shù)
Date date3=new Date();
long date3Time = date3.getTime();
//當前時間-(輸入時間-基準時間)=你的年齡
long day=(date3Time-(date2Time-date1Time))/1000/60/60/24;
long year=(date3Time-(date2Time-date1Time))/1000/60/60/24/365;
System.out.println("你的年齡為:"+year+"歲");
}
}
我們可以看到征唬,在上面的輸入過程中就要輸“yyyy-MM-dd HH:ss:mm”捌显,顯的很麻煩,我們通常都不使用時分秒鳍鸵。
但是在Jdk8中提供了很多新特性
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class LocalDateYear {
public static void main(String[] args) {
//鍵盤錄入一個人的生日
/*
剛才我們使用了jdk1.8以前版本苇瓣,現(xiàn)在使用新特性來完成,將使用atTime
*/
Scanner sc=new Scanner(System.in);
System.out.println("請輸入你的生日偿乖,格式為xxxx-xx-xx");
String birthday=sc.nextLine();
//這里我們不需要時分秒击罪,我們需要的是年月日,因此我們只需要格式化成年月日即可
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDat1 = LocalDate.parse(birthday,dateTimeFormatter);
//new一個當前的年月日
LocalDate localDate2 = LocalDate.now();
//使用period就可以獲得年份
Period period = Period.between(localDat1, localDate2);
System.out.println("你的年齡為"+period.getYears()+"歲");
}
}