0

您好,我正在尝试计算怀孕期还剩多少天,但我认为我的算法不正确

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);
   }

我基于 280 天期限,getDueDate()是一个 Date 对象并getTime()返回毫秒 unix 时间

在现实世界的某些日子里,报告的数字有时会偏离 1,我开始认为我的算法是错误的,或者毫秒时间越来越远,或者毫秒时间不够精确,或者公历日历功能很奇怪。

总而言之,我不确定,任何见解都值得赞赏

4

1 回答 1

5

我不知道你的算法,但这(基本上)是我在跟踪我妻子怀孕时使用的算法......书呆子......

为自己节省大量“猜测”工作并掌握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);

    }
}

这将输出...

dueDate = 2014-02-25T14:14:31.159+11:00
Days remaining = 279
Days In = 1
Week = 0.1
于 2013-05-21T04:18:17.083 回答