繁体   English   中英

计算年,月,日,小时,分钟和秒的年龄

[英]Calculate age in Years, Months, Days, Hours, Minutes, and Seconds

我需要用户输入的生日(最好是dd/mm//yyyy格式)并根据今天的日期查找他们的年龄。 有人可以向我解释一下我应该找到的这个过程吗? 我需要以以下格式打印出来:

“你是19岁,4个月,12天,8小时,44分钟,39秒。”

我对如何从另一个日期减去日期感到困惑,以及我将如何分别引用每个部分(年,月,日,小时等)。

我现在的代码供参考:

import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

public class Driver {

    public Driver(){}

    public static void main( String[] args){
    Driver menu = new Driver();
    MenuOptions option;
    do{
        menu.displayMenu();
        option = menu.getResponse();
        menu.runOption(option);
    }while(option != MenuOptions.Quit);  
    }

    private enum MenuOptions{
    AgeCalc("Calculate your age"),
        AnniversaryCalc("Calculate time until specified date"),
        AgeDifference("Find the time between two specified dates"),
        Quit("Exit the program");

    private String value;

    private MenuOptions(String value){
        this.value = value;
    }

    public String toString(){
        return value;
    }
    }

    public void displayMenu(){
    for(MenuOptions option : MenuOptions.values()){
        System.out.printf("%5d: %s\n", option.ordinal()+1, option);
    }
    }

    public MenuOptions getResponse(){
    int value = -1;
    Scanner input = new Scanner(System.in);

    do{
        System.out.println("> ");
        String response = input.nextLine();

        if(response.matches("\\d+")){
        value = Integer.parseInt(response);
        if(value < 1 || value > MenuOptions.values().length){
            value = -1;
            System.out.println("Unknown response, please enter a number between 1 and " +MenuOptions .values().length);
        }
        }

    }while(value <=0);

    return MenuOptions.values()[value-1];
    }

    public void runOption(MenuOptions option){
    Scanner in = new Scanner(System.in);

    switch(option){
    case AgeCalc:
        System.out.println("Please enter your birthday mm/DD/yyyy).");
        System.out.println(">");

        DateFormat df = new SimpleDateFormat("mm/DD/yyyy");

        try
        {
            java.util.Date birthday = df.parse(in.nextLine());           
            System.out.println("Today = " + df.format(birthday));
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        Calendar today = Calendar.getInstance();
        java.util.Date today = df.format();

        DateFormat simple = new SimpleDateFormat("dd/MM/yyyy");
        String birthdate = simple.format(in.nextLine());
        Date.parse(birthdate);

        System.out.println(birthdate.toString());
        break;
    case AnniversaryCalc:
        System.out.printf("PI: %.20f\n", Math.PI);
        break;
    case AgeDifference:
        for(int p=0; p <= 32; p++){
        System.out.println("2^" +p+" = " +Math.pow(2,p));
        }
    }
    }
}

我建议使用Joda时间 这是一个比JDK中包含的API更好的API。

创建一个表示该人出生的瞬间 ,另一个表示当前时间的Instant ,并使用这两个Instant创建一个期间 从那里,您可以使用Period类中提供的方法轻松获取所需的字段。

java.time

使用Java 8及更高版本中内置的java.time框架。 示例是直接从Tutorial复制粘贴(稍作修改)。

import java.time.Period
import java.time.LocalDate
import java.time.format.DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");    
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.parse("1/1/1960", formatter);


Period p = Period.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                   " months and " + p.getDays() +
                   " days old.");

代码生成类似于以下内容的输出:

你是53岁,4个月和29天。

在我看来,输出小时,分钟和秒是没有意义的,因为你的数据库中可能没有这么精确的数据。 这就是为什么示例使用LocalDate而不是LocalDateTime

有几种方法。 我会使用joda-time ,使用Period类来表示今天和出生日期之间的差值。 它提供您想要的功能。

如果您不想处理第三方库,那么获取表示相关两个日期的Date对象并在两者上调用getTime() ,从最早的数据中减去最新数据,并且您将获得日期之间的增量(以毫秒为单位) 。 将其转换为年/月/日等的数学计算是微不足道的。*类似于:

delta /= 1000;  // convert ms to s
if (delta > 60 * 60 * 24 * 365) // number of seconds in a year
    int years = delta / (60 * 60 * 24 * 365) // integer division to get the number of years
    delta %= (60 * 60 * 24 * 365) // assign the remainder back to delta
// repeat ad nauseum
  • 当我说琐碎时,我的意思是看似简单但却充满了棘手的细节,比如一个月的定义是什么(30天?365/12天?)以及你如何处理闰年和夏令时以及时区。 就个人而言,我坚持使用joda-time。
public class Main {
    public static void main(String[] args) {
    LocalDateTime dateTime = LocalDateTime.of(2018, 12, 27, 11, 45, 0);
            Duration showSeconds = AgeCalculator.calculateAgeDuration(dateTime, LocalDateTime.now());
            TimeConverter.calculateTime(showSeconds.getSeconds());
    }
}

public class AgeCalculator {
    public static Duration calculateAgeDuration(LocalDateTime dayBefore, LocalDateTime currentDay) {
            return Duration.between(dayBefore, currentDay);
    }
}

public class TimeConverter {
    public static void calculateTime(long timeSeconds) {
        long days = timeSeconds / 86400; // 24*60*60
        long hours = timeSeconds / 3600;
        long minutes = (timeSeconds % 3600) / 60;
        long seconds = (timeSeconds % 3600) % 60;

        System.out.println("Days: " + days);
        System.out.println("Hours: " + hours);
        System.out.println("Minutes: " + minutes);
        System.out.println("Seconds: " + seconds);
    }
}

天:0小时:4分钟:30秒:29

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM