如何使用java中的月日,yyyy的格式从dob计算年龄?前任。 (1999 年 3 月 2 日)

时间:2021-08-01 15:16:57

标签: java

以下当前代码使用 yyyy-mm-dd 格式。然而,输入应该是这样的(1999 年 3 月 2 日)。我如何计算或转换它?

public class CalculateAgeJava8 {
 
    public static void main(String[] args) {
        System.out.print("Please enter date of birth: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        scanner.close();
 
        LocalDate dob = LocalDate.parse(input);
        System.out.println("Age is:" + getAge(dob));
    }
 
    public static int getAge(LocalDate dob) {
        LocalDate curDate = LocalDate.now();
        return Period.between(dob, curDate).getYears();
    }
 
}

2 个答案:

答案 0 :(得分:5)

您可以在这种情况下使用 java.time.format.DateTimeFormatter

class CalculateAgeJava8 {

    public static void main(String[] args) {
        System.out.print("Please enter date of birth: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        scanner.close();

        DateTimeFormatter fm = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);

        LocalDate dob = LocalDate.parse(input, fm);
        System.out.println(dob);
        System.out.println("Age is:" + getAge(dob));
    }

    public static int getAge(LocalDate dob) {
        LocalDate curDate = LocalDate.now();
        return Period.between(dob, curDate).getYears();
    }

}

答案 1 :(得分:5)

您需要一个 void _answerQuestion() { final newIndex = _questionIndex + 1; // This will make sure the [_questionIndex] does not exceed the available range. if (newIndex < questions.length) { setState(() { _questionIndex = _questionIndex + 1; }); } print(_questionIndex); } 来解析指定格式的日期字符串,例如

DateTimeFormatter

示例运行:

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Scanner;

public class CalculateAgeJava8 {

    public static void main(String[] args) {
        System.out.print("Please enter date of birth in the format MMMM d, yyyy (e.g. March 2, 1999): ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);

        LocalDate dob = LocalDate.parse(input, dtf);
        System.out.println("Age is:" + getAge(dob));
    }

    public static int getAge(LocalDate dob) {
        LocalDate curDate = LocalDate.now();
        return Period.between(dob, curDate).getYears();
    }    
}

在这里,您可以使用 Please enter date of birth in the format MMMM d, yyyy (e.g. March 2, 1999): March 2, 1999 Age is:22 代替 y,而是使用 I prefer u to y

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。

注意: 永远不要关闭 u,因为它也会关闭 Scanner(System.in) 并且除了重新启动 JVM 之外没有办法再次打开它,这意味着如果其他部分的应用程序正在使用 System.in,这将导致异常。