java calculate pregnancy algorithm [duplicate]

元气小坏坏 提交于 2020-01-07 04:55:31

问题


hello I am trying to calculate how many days are left in a pregnancy term but I think my algorithm is incorrect

public int getDaysPregnantRemainder_new() {
    GregorianCalendar calendar = new GregorianCalendar();
   calendar.set(Calendar.HOUR_OF_DAY, 0);
  calendar.set(Calendar.MINUTE, 0);
   calendar.set(Calendar.SECOND, 0);
   long diffDays = 280 - ((getDueDate().getTime() - calendar.getTime()
  .getTime()) / (24 * 60 * 60 * 1000));
  return (int) Math.abs((diffDays) % 7);
   }

I am basing it off of a 280 day term, getDueDate() is a Date object and getTime() returns millisecond unix time

On some real world days the number reported is off by one, sometimes, and I am starting to think my algorithm is just wrong, or the millisecond time get gradually further and further off, or the millisecond time is not precise enough, or the gregorian calendar function rounds weird.

All in all I'm not sure, any insight appreciated


回答1:


I don't know about your algorithm, but this (is basically) the one I used while tracking my wife's pregency...nerds...

Save yourself a lot of "guess" work and get hold of Joda-Time

public class TestDueDate {

    public static final int WEEKS_IN_PREGNANCY = 40;
    public static final int DAYS_IN_PREGNANCY = WEEKS_IN_PREGNANCY * 7;

    public static void main(String[] args) {

        DateTime dueDate = new DateTime();
        dueDate = dueDate.plusDays(DAYS_IN_PREGNANCY);

        System.out.println("dueDate = " + dueDate);

        DateTime today = DateTime.now();

        Days d = Days.daysBetween(today, dueDate);

        int daysRemaining = d.getDays();

        int daysIn = DAYS_IN_PREGNANCY - daysRemaining;

        int weekValue = daysIn / 7;
        int weekPart = daysIn % 7;

        String week = weekValue + "." + weekPart;

        System.out.println("Days remaining = " + daysRemaining);
        System.out.println("Days In = " + daysIn);
        System.out.println("Week = " + week);

    }
}

This will output...

dueDate = 2014-02-25T14:14:31.159+11:00
Days remaining = 279
Days In = 1
Week = 0.1


来源:https://stackoverflow.com/questions/16661971/java-calculate-pregnancy-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!