Java中的年龄计算 [英] age calculation in Java

查看:165
本文介绍了Java中的年龄计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小命令行java应用程序,它允许输入日期并将其与当前日期进行比较,并返回一个整数,表示输入日期和当前日期之间的年数。这是用多年来计算一个活人的年龄。到目前为止,我发现我需要使用Calendar对象,但我无法弄清楚如何从当前年份中减去输入的年份并返回一个整数。你能帮我吗?只是达到了比较日期的机制上的高点。谢谢。

i'm trying to create a small command line java app that will allow the input of a date and compare it to the current date and return an integer that represents the number of years between the entered date and the current date. this is to calculate the age of a living person in years. So far, I've found that I need to use the Calendar object, but I can't figure out how to subtract the entered year from the current year and return an integer. Can you help? Just hit the high points on the mechanics of comparing the dates. Thanks.

推荐答案

一旦你有一个日历对象初始化正确日期,您可以调用 get(Calendar.YEAR)值来获取表示年份的整数。对两个日期执行此操作并减去。

Once you have a Calendar object initialized with the correct date, you can call the get(Calendar.YEAR) value to get an integer representing the year. Do this for both dates and subtract.

您还需要获取月份和日期并进行比较,因为如果结束日期的月份/日期低于开始,然后你会想要从之前的结果中减去1(年份尚未完成)。

You'll also want to get the month and date and compare, because if the end date has a lower month/date than the start, then you'll want to subtract 1 from the earlier result (the year has not yet been completed).

通常对于生日,你不关心时间组件(小时/分钟/秒),因此一些库可能会给你一个不同的结果(极少数)案例) - 在这种情况下推出自己的案件是合理的。

Typically for birthdays you don't care about the time component (hour/minute/second), so some libraries may give you a different result (in an extremely small number of cases) -- it's justifiable to roll your own for this case.

这篇关于Java中的年龄计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆