Given an input as the date of birth of the person, write a program to calculate on which day (MONDAY, TUESDAY….) he was born to store and print the day in Upper Case letters.
The return type of the output is a string which should be the day on which the person was born.
NOTE: date format should be(dd-MM-yyyy)
Input and Output Format
- Input consists of a date string.
- The output is a string which the day on which the person was born.
Refer sample output for formatting specifications
Sample Input 1:
29-07-2013
Sample Output 1:
MONDAY
Sample Input 2:
14-12-1992
Sample Output 2:
MONDAY
Program to find the day of birth in Java
Following are the steps to find the day of birth in Java:
- Input a string from the user.
- Pass the string to calculateBornDay() method.
- Inside the method, first, create the object of SimpleDateFormat with a given pattern. Then, parse the string to produce a date.
- Now, create one more instance of SimpleDateFormat with a given pattern. By using this instance, format the date specified into a string.
- At last, return the string.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Main { public static void main(String[] args) throws ParseException { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); System.out.println(calculateBornDay(s1)); } public static String calculateBornDay(String s1) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); SimpleDateFormat sdf1 = new SimpleDateFormat("EEEEE"); Date d = sdf.parse(s1); String s = sdf1.format(d); return s.toUpperCase(); } }
Output
Program to Calculate Age from Date of Birth using Period class
Period Class: A date-based amount of time in the ISO-8601 calendar system. In Java 8, the Period class is used to store the difference between the two local date instances.
Refer sample output for formatting specifications
Sample Input :
[Input is provided in the program]
Sample Output :
Years: 27
Months: 11
Days: 11
Following are the steps to find the age using the Period class in Java:
- First, get the current date from the system clock using LocalDate. And, pass the year, month, and date.
- Now, use the Period class to find the difference between the two LocalDate instances.
- Print years, months and days using getYears(), getMonths() and getDays().
package com.demo2; import java.time.LocalDate; import java.time.Month; import java.time.Period; public class CalculateAge { public static void main(String[] args) { LocalDate now = LocalDate.now(); LocalDate born = LocalDate.of(1994, Month.FEBRUARY,2); Period period = Period.between(born,now); System.out.println("Years: "+period.getYears()); System.out.println("Months: "+period.getMonths()); System.out.println("Days: "+period.getDays()); } }
Output
Thus, in this way, we learn how to calculate the day of birth in Java.