从日历类Java获取生日

编程
import java.util.Calendar;

public class Person {

    private Calendar dob = Calendar.getInstance();
    private String name;
    private int phoneNum;


    public Person (String name, int birthYear, int birthMonth, int birthDate) {
        this.name = name;
        this.dob.set(birthYear, birthMonth, birthDate);
    }

    public Calendar getDob() {
        return dob;
    }
    public void setDob(Calendar dob) {
        this.dob = dob;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPhoneNum() {
        return phoneNum;
    }
    public void setPhoneNum(int phoneNum) {
        this.phoneNum = phoneNum;
    }

    // I want this to return true if today is my birthday
    public boolean isCurrentDayInMonthSameAsBirthDayInMonth() {
        if (Calendar.DAY_OF_MONTH == this.dob.get(this.dob.DAY_OF_MONTH)) {
            return true;
        }
        else { 
            return false;
        }
    }

    // I want this to return true if the month is the same as my birth month
    public boolean isCurrentMonthSameAsBirthMonth() {
        if (Calendar.MONTH == this.dob.get(this.dob.MONTH)) {
            return true;
        }
        else {
            return false;
        }
    }

}

抱歉,格式不正确,但我需要帮助的所有内容均已正确格式化。我需要帮助将Dob设置为所需的任何日期,然后进行测试以查看它是我的生日还是该月与我的出生月份相同。谢谢!

帕斯勒

您有两个问题:

  1. Calendar.MONTH一月份从0开始,而Calendar.DAY_OF_MONTH从1开始。所以您需要this.dob.set(birthYear, birthMonth-1, birthDate);
  2. Calendar.DAY_OF_MONTH并且Calendar.MONTH是字段索引,而不是今天的日期和月份。您需要创建一个“今天”的Calendar实例并对其进行测试Calendar.getInstance().get(Calendar.DAY_OF_MONTH)

正如@matoni也建议的那样,您可以缩短检查方法。@Andreas为测试方法找到了一个更好的名字:

// I want this to return true if today is my birthday
public boolean isCurrentDayInMonthSameAsBirthDayInMonth() {
    return isSameAsToday(Calendar.DAY_OF_MONTH);
}

// I want this to return true if the month is the same as my birth month
public boolean isCurrentMonthSameAsBirthMonth() {
    return isSameAsToday(Calendar.MONTH);
}

private boolean isSameAsToday(int field){
    return Calendar.getInstance().get(field) == this.dob.get(field);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章