本文介绍了如何创建一个计算两个日期得到一个人的年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让,将计算一个人的年龄的方法。我想计算下的第二个公开
静态
INT $ C $完成C>
getAge
。如果对方是当前日期之后出生的我希望它打印出错误-1。
我如何比较这两种 SimpleDate
值 dateBd
和 dateRef
,以获得对年龄int值?
公共静态SimpleDate今日(){
日历todayCal = Calendar.getInstance();
SimpleDate todayDate =新SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH)+ 1,
todayCal.get(Calendar.DATE)
todayCal.get(Calendar.YEAR));
返回todayDate;
公共静态INT getAge(SimpleDate dateBd){
INT年龄;
SimpleDate dateToday = TODAY();
年龄= getAge(dateBd,dateToday);
返回年龄;
公共静态INT getAge(SimpleDate dateBd,SimpleDate dateRef){
如果(getAge(dateBd)> getAge(dateRef)){
的System.out.println(错误);
}
返回-1;
解决方案
什么是SimpleDate?反正在这里让你开始的东西
进口java.util.GregorianCalendar中;
进口的java.util.Calendar;
公共类CalcAge {
公共静态无效的主要(字串[] args){
//记得...个月是基础:一月= 0二月= 1 ...
的System.out.println
(1962年11月11日:+年龄(1962,10,11));
的System.out.println
(1999年12月3日:+年龄(1999,11,3));
}
私有静态诠释年龄(INT Y,INT男,INT D){
日历CAL =新的GregorianCalendar(Y,M,D);
日历现在=新的GregorianCalendar();
INT RES = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
如果((cal.get(Calendar.MONTH)> now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH)== now.get(Calendar.MONTH)
&功放;&安培; cal.get(Calendar.DAY_OF_MONTH)> now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
返回水库;
}
}
I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public
static
int
getAge
. If the person is born after the current date i want it to print out error -1.
How do I compare the two SimpleDate
values dateBd
and dateRef
in order to get an int value for age?
public static SimpleDate today() {
Calendar todayCal = Calendar.getInstance();
SimpleDate todayDate = new SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,
todayCal.get(Calendar.DATE),
todayCal.get(Calendar.YEAR));
return todayDate;
public static int getAge(SimpleDate dateBd) {
int age;
SimpleDate dateToday = today();
age = getAge(dateBd, dateToday);
return age;
public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {
if(getAge(dateBd)>getAge(dateRef)){
system.out.println("error");
}
return -1;
解决方案
What is SimpleDate ? Anyway here something to get you started
import java.util.GregorianCalendar;
import java.util.Calendar;
public class CalcAge {
public static void main(String [] args) {
// remember ... months are 0-based : jan=0 feb=1 ...
System.out.println
("1962-11-11 : " + age(1962,10,11));
System.out.println
("1999-12-03 : " + age(1999,11,3));
}
private static int age(int y, int m, int d) {
Calendar cal = new GregorianCalendar(y, m, d);
Calendar now = new GregorianCalendar();
int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
return res;
}
}
这篇关于如何创建一个计算两个日期得到一个人的年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!