0

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

CQM
  • 42,592
  • 75
  • 224
  • 366

1 Answers1

5

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
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366