Pregnancy Due Date Calculator in Java
There are number of ways to calculate pregnancy due date. The most common way is to add 280 days to the first day of the last menstrual period. For example, if the first day of last menstrual period is 10th February 2017, the estimated delivery date is 17th November 2017. Note that pregnancy due dates are approximate.
Java Program to Calculate Pregnancy Due Date (Java 8)
The following example program in Java predicts the pregnancy due date. This example is written in Java 8 using the new java.time.LocalDate class. This program also demonstrates the use of DateTimeFormatter for formatting date.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Scanner; // Java program to calculate pregnancy due date public class PregnancyDueDateCalculator { public static void main(String[] args) throws Exception{ System.out.print("Please enter first day of last menstrual period in YYYY-MM-DD: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); LocalDate date = LocalDate.parse(input); date = date.plusDays(280); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd MMM yyyy"); System.out.println("Pregnancy due date is: "+date.format(fmt)); } }
The sample output from the Java program is given below,
java PregnancyDueDateCalculator
Please enter first day of last menstrual period in YYYY-MM-DD: 2017-02-10
Please enter first day of last menstrual period in YYYY-MM-DD: 2017-02-10
Pregnancy due date is: 17 Nov 2017