已知出生日期如何計算年齡?使用Java?


Java在`java.time`包中提供了一個名為**Period**的類。它用於計算兩個給定日期之間的時間段(例如,天數、月數和年數)。

此類的**between()**方法接受兩個**LocalDate**物件,並計算這兩個給定日期之間的時間段(年數、月數和天數),並將其作為Period物件返回。

您可以分別使用getDays()、getMonths()和getYears()方法提取此期間的天數、月數和年數。

計算年齡

如果您已經知道一個人的出生日期,要計算其年齡:

  • 從使用者處獲取出生日期。
  • 將其轉換為**LocalDate**物件。
  • 獲取當前日期(作為LocalDate物件)。
  • 使用**between()**方法計算這兩個日期之間的時間段:
Period period = Period.between(dateOfBirth, LocalDate.now());
  • 使用getDays()、getMonths()和getYears()方法從Period物件中獲取天數、月數和年數:

period.getYears();
period.getMonths();
period.getDays();

示例

下面的示例從使用者處讀取姓名和出生日期,將其轉換為**LocalDate**物件,獲取當前日期,計算這兩個日期之間的時間段,並將其作為天數、月數和年數打印出來。

 線上演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class CalculatingAge {
   public static Date StringToDate(String dob) throws ParseException{
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Parsing the given String to Date object
      Date date = formatter.parse(dob);
      System.out.println("Date object value: "+date);
      return date;
   }
   public static void main(String args[]) throws ParseException {
      //Reading name and date of birth from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      //Converting String to Date
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date date = formatter.parse(dob);
      //Converting obtained Date object to LocalDate object
      Instant instant = date.toInstant();
      ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
      LocalDate givenDate = zone.toLocalDate();
      //Calculating the difference between given date to current date.
      Period period = Period.between(givenDate, LocalDate.now());
      System.out.print("Hello "+name+" your current age is: ");
      System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
   }
}

輸出

Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-07-1989
Hello Krishna your current age is: 29 years 10 and 5 days

更新於:2020-06-29

5K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.