Hello geeks, today we are going to make an application to calculate Age or time period between two dates. By making this application one can calculate his/her exact age, also one can calculate the exact difference between two dates.
Prerequisites:
Before making this application, you can go through the article Program to calculate age to have a better understanding of the concepts used in this application.
What we are going to build in this article?Â
In this application, we will be using two DatePickers, where user can select the date no. 1 and 2 respectively. A Button is used to perform the calculation part and show the result in a TextView named as result. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Creating a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?Â
Step 2: Navigate to Build scripts > build.gradle(module) file and add the following dependency to it
implementation 'joda-time:joda-time:2.9.1'
Step 3: Working with the activity_main.xml file
Here we will design the user interface of our application. We will be using the following components for their respective works:
- Button 1: to pick the first date user wants to enter.
- Button 2: to pick the second date user wants to enter.
- Button 3: to perform the calculation
- TextView: to show the final output(age).
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!-- Parent layout as linear layout--> < LinearLayout     android:layout_width = "match_parent"     android:layout_height = "match_parent"     android:gravity = "center"     android:orientation = "vertical"     android:padding = "10dp"     tools:context = ".MainActivity" > Â
    <!-- linear layout to show datepickers-->     < LinearLayout         android:layout_width = "match_parent"         android:layout_height = "wrap_content" > Â
        <!-- to select the first date-->         < Button             android:id = "@+id/bt_birth"             android:layout_width = "150dp"             android:layout_height = "50dp"             android:background = "@android:color/transparent"             android:drawableRight = "@drawable/ic_baseline"             android:text = "01/01/2021"             android:textColor = "@color/black"             android:textSize = "13sp" /> Â
        <!-- displaying message as "to"-->         < TextView             android:layout_width = "100dp"             android:layout_height = "50dp"             android:gravity = "center_horizontal"             android:text = "To"             android:textColor = "@color/black"             android:textSize = "20sp"             android:textStyle = "bold" /> Â
        <!-- to display date number 2-->         < Button             android:id = "@+id/bt_today"             android:layout_width = "145dp"             android:layout_height = "50dp"             android:background = "@android:color/transparent"             android:drawableRight = "@drawable/ic_baseline"             android:textColor = "@color/black"             android:textSize = "13sp" />              </ LinearLayout >     <!-- to perform the calculation-->     < Button         android:id = "@+id/btn_calculate"         android:layout_width = "wrap_content"         android:layout_height = "wrap_content"         android:layout_marginTop = "10dp"         android:text = "calculate" /> Â
    <!-- to display the message "Result"-->     < TextView         android:layout_width = "wrap_content"         android:layout_height = "wrap_content"         android:layout_marginTop = "50dp"         android:text = "Result"         android:textColor = "@android:color/holo_blue_bright"         android:textSize = "30sp"         android:textStyle = "bold" /> Â
    <!-- To show the final output(age)-->     < TextView         android:id = "@+id/tv_result"         android:layout_width = "wrap_content"         android:layout_height = "wrap_content"         android:layout_marginTop = "10dp"         android:text = "0 Years | 0 Months | 0 Days"         android:textSize = "25sp"         android:textStyle = "bold" /> Â
</ LinearLayout > |
After implementing the above code, the design of the activity_main.xml file looks like this.
Step 4: Working with MainActivity.java file
In MainActivity.java file onClickListener is used on buttons to pick the date and to perform the calculation. Use the following code in the MainActivity.java file.
Java
import android.app.DatePickerDialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.Toast; Â
import androidx.appcompat.app.AppCompatActivity; Â
import org.joda.time.Period; import org.joda.time.PeriodType; Â
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; Â
public class MainActivity extends AppCompatActivity { Â
    // initializing variables     Button btn_birth, btn_today, btn_calculate;     TextView tvResult;     DatePickerDialog.OnDateSetListener dateSetListener1, dateSetListener2; Â
    @Override     protected void onCreate(Bundle savedInstanceState) {         super .onCreate(savedInstanceState);         setContentView(R.layout.activity_main); Â
        // assign variables         btn_birth = findViewById(R.id.bt_birth);         btn_today = findViewById(R.id.bt_today);         btn_calculate = findViewById(R.id.btn_calculate);         tvResult = findViewById(R.id.tv_result); Â
        // calendar format is imported to pick date         Calendar calendar = Calendar.getInstance();                  // for year         int year = calendar.get(Calendar.YEAR);                  // for month         int month = calendar.get(Calendar.MONTH);                  // for date         int day = calendar.get(Calendar.DAY_OF_MONTH); Â
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "dd/MM/yyyy" ); Â
        // to set the current date as by default         String date = simpleDateFormat.format(Calendar.getInstance().getTime());         btn_today.setText(date); Â
        // action to be performed when button 1 is clicked         btn_birth.setOnClickListener( new View.OnClickListener() {             @Override             public void onClick(View view) {                 // date picker dialog is used                 // and its style and color are also passed                 DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity. this , android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener1, year, month, day                 );                 // to set background for datepicker                 datePickerDialog.getWindow().setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT));                 datePickerDialog.show();             }         }); Â
        // it is used to set the date which user selects         dateSetListener1 = new DatePickerDialog.OnDateSetListener() {             @Override             public void onDateSet(DatePicker view, int year, int month, int day) {                 // here month+1 is used so that                 // actual month number can be displayed                 // otherwise it starts from 0 and it shows                 // 1 number less for every month                 // example- for january month=0                 month = month + 1 ;                 String date = day + "/" + month + "/" + year;                 btn_birth.setText(date);             }         }; Â
        // action to be performed when button 2 is clicked         btn_today.setOnClickListener( new View.OnClickListener() {             @Override             public void onClick(View view) {                 // date picker dialog is used                 // and its style and color are also passed                 DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity. this , android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener2, year, month, day                 );                 // to set background for datepicker                 datePickerDialog.getWindow().setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT));                 datePickerDialog.show();             }         }); Â
        // it is used to set the date which user selects         dateSetListener2 = new DatePickerDialog.OnDateSetListener() {             @Override             public void onDateSet(DatePicker view, int year, int month, int day) {                 // here month+1 is used so that                 // actual month number can be displayed                 // otherwise it starts from 0 and it shows                 // 1 number less for every month                 // example- for january month=0                 month = month + 1 ;                 String date = day + "/" + month + "/" + year;                 btn_today.setText(date);             }         }; Â
        // action to be performed when calculate button is clicked         btn_calculate.setOnClickListener( new View.OnClickListener() {             @Override             public void onClick(View view) {                 // converting the inputted date to string                 String sDate = btn_birth.getText().toString();                 String eDate = btn_today.getText().toString();                 SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat( "dd/MM/yyyy" );                 try {                     // converting it to date format                     Date date1 = simpleDateFormat1.parse(sDate);                     Date date2 = simpleDateFormat1.parse(eDate); Â
                    long startdate = date1.getTime();                     long endDate = date2.getTime(); Â
                    // condition                     if (startdate <= endDate) {                         org.joda.time.Period period = new Period(startdate, endDate, PeriodType.yearMonthDay());                         int years = period.getYears();                         int months = period.getMonths();                         int days = period.getDays(); Â
                        // show the final output                         tvResult.setText(years + " Years |" + months + "Months |" + days + "Days" );                     } else {                         // show message                         Toast.makeText(MainActivity. this , "BirthDate should not be larger than today's date!" , Toast.LENGTH_SHORT).show();                     }                 } catch (ParseException e) {                     e.printStackTrace();                 }             }         });     } } |
Congratulations! we have successfully the application to calculate the age or difference between two dates. Here is the final output of our application.
Output: