-1

我有一个人的出生日期。还有一个日期,比如 d1。我想知道这个人是否在 d1 日期的最后一年内达到 40 岁。日期为“yyyyMMdd”格式

我想到了一些与找出时间和做一些减法有关的事情,然后检查它是否是 40 等等。

进行此计算的最佳方法是什么?

4

4 回答 4

1

有很多方法可以实现这一点,从使用毫秒和简单的减法和转换到年到使用Calendar对象。

您可能还想看看joda-time(一个方便的 3rd 方 java api 来处理日期)和

这是一种使用日历的方法

@Test
public void compareDates() throws ParseException {
    Date d1 = new SimpleDateFormat("yyyyMMdd").parse("20130317");
    Date birthDate1 = new SimpleDateFormat("yyyyMMdd").parse("19700101");
    Date birthDate2 = new SimpleDateFormat("yyyyMMdd").parse("19900101");

    GregorianCalendar cd1 = new GregorianCalendar();
    cd1.setTime(d1);
    cd1.set(Calendar.YEAR, cd1.get(Calendar.YEAR)-1); // one year ago

    GregorianCalendar cbd1 = new GregorianCalendar();
    cbd1.setTime(birthDate1);

    GregorianCalendar cbd2 = new GregorianCalendar();
    cbd2.setTime(birthDate2);

    Assert.assertTrue((cd1.get(Calendar.YEAR) - cbd1.get(Calendar.YEAR)) > 40);
    Assert.assertFalse((cd1.get(Calendar.YEAR) - cbd2.get(Calendar.YEAR)) > 40);
}
于 2013-03-17T19:40:26.170 回答
0

getTime()将以毫秒为单位返回时间。

long diff = d2.getTime() - d1.getTime(); // the difference in milliseconds

我将把这些毫秒转换为年作为一种练习。

于 2013-03-17T19:12:07.733 回答
0
public class DateTester{

    private static final long MILLISECONDS_IN_YEAR = 31556926279L;

    public static void main(String[] args) {
            //Note:  These constructors are deprecated
            //I'm just using them for a quick test

    Date startDate = new Date(2013,03,01);
    Date birthday = new Date(1981,01,1981);//Returns false
    Date birthday2 = new Date(1972,03,20); //Returns true
    Date birthday3 = new Date(1973,02,27); //Test edge cases  //Returns false
    Date birthday4 = new Date(1972,02,27); //Test edge cases, //Returns false


    System.out.println(withinYear(birthday, startDate,40));
    System.out.println(withinYear(birthday2, startDate,40));
    System.out.println(withinYear(birthday3, startDate,40));
    System.out.println(withinYear(birthday4, startDate,40));


        System.out.println(withinYear(birthday, startDate,40));
        System.out.println(withinYear(birthday2, startDate,40));
    }

    public static boolean withinYear(Date birthday, Date startDate, int years){
        if(birthday.before(startDate)){
            long difference = Math.abs(birthday.getTime() - startDate.getTime());
            int yearDifference = (int) (difference/MILLISECONDS_IN_YEAR);
            return yearDifference  < (years +1) && yearDifference >= years;
        }
        return false;
    }
}
于 2013-03-17T20:06:32.960 回答
0
于 2017-05-03T09:54:03.120 回答