java 以年、月、日、小时、分钟和秒为单位计算年龄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4710206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate age in Years, Months, Days, Hours, Minutes, and Seconds
提问by Chris V.
I need to take a birthday entered by the user (preferably in dd/mm//yyyy
format) and find their age, based on todays date. Could someone explain to me the process I should go through to find this? I need to print it out in the format:
我需要根据用户输入的生日(最好是dd/mm//yyyy
格式)并根据今天的日期找到他们的年龄。有人可以向我解释我应该经历的过程吗?我需要按以下格式打印出来:
"You are 19 years, 4 months, 12 days, 8 hours, 44 minutes, and 39 seconds old."
“你19岁4个月12天8小时44分39秒。”
I'm just a little confused on how I would subtract a date from another date, and how I would reference each part (years, months, days, hours, etc) separately.
我对如何从另一个日期中减去一个日期以及如何分别引用每个部分(年、月、日、小时等)感到有些困惑。
The code I have at the moment for reference:
我现在有的代码供参考:
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));
}
}
}
}
回答by Brad Mace
I'd suggest using Joda time. It's a much better API than what's included in the JDK.
我建议使用Joda time。它是一个比 JDK 中包含的 API 好得多的 API。
Create an Instantrepresenting when the person was born, another representing the current time, and use those two Instant
s to create a Period. From there it's easy to get the fields you need using the methodsprovided in the Period
class.
创建一个Instant表示这个人的出生时间,另一个表示当前时间,并使用这两个Instant
s 创建一个Period。从那里可以使用类中提供的方法轻松获取所需的字段Period
。
回答by Przemek
java.time
时间
Using the java.time
framework built into Java 8 and later. Example is copy pasted directly from Tutorial(with small modifications).
使用java.time
内置于 Java 8 及更高版本中的框架。示例是直接从教程中复制粘贴的(稍作修改)。
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.");
The code produces output similar to the following:
该代码生成类似于以下内容的输出:
You are 53 years, 4 months and 29 days old.
您今年 53 岁零 4 个月零 29 天。
In my opinion it doesn't make sense to output hour, minutes and seconds because you probably won't have such precise data in your DB. That is why example uses LocalDate
instead of LocalDateTime
.
在我看来,输出小时、分钟和秒是没有意义的,因为您的数据库中可能没有如此精确的数据。这就是示例使用LocalDate
而不是LocalDateTime
.
回答by Stewart Murrie
There are a couple of ways. I would use joda-time, using the Periodclass to represent the delta between today and the date of birth. It provides exactly the capability you want.
有几种方法。我会使用joda-time,使用Period类来表示今天和出生日期之间的增量。它提供了您想要的功能。
If you don't want to deal with a 3rd party library, then get Date
objects representing the two dates in question and call getTime()
on both, subtract the latest from the earliest and you'll have the delta between the dates in milliseconds. The maths to convert that into years/months/days etc is trivial.* Something like:
如果您不想处理第 3 方库,则获取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
- When I say trivial, I mean seemingly straightforward but full of tricky details, like what the definition of a month is (30 days? 365/12 days?) and how you deal with leap years and daylight savings and timezones. Personally, I'd stick with joda-time.
- 当我说琐碎时,我的意思是看似简单但充满棘手的细节,例如一个月的定义是什么(30 天?365/12 天?)以及您如何处理闰年、夏令时和时区。就个人而言,我会坚持使用 joda-time。
回答by Ilya Budu
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);
}
}
Days: 0 Hours: 4 Minutes: 30 Seconds: 29
天数:0 小时:4 分钟:30 秒:29