To get the current Time and Date in our android application, follow the below steps:
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/idRLContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--on below line we are creating
a text for our app-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/idTVCurrent"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:gravity="center"
android:padding="10dp"
android:text="Current Date and Time in Android"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!--on below line we are creating a text view-->
<TextView
android:id="@+id/idTVCurrent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:gravity="center"
android:padding="10dp"
android:text="Time"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3: Working with the MainActivity file
Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail.
package com.gtappdevelopers.kotlingfgproject;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// on below line we are creating variables.
private TextView currentTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// on below line we are initializing our variables.
currentTV = findViewById(R.id.idTVCurrent);
// on below line we are creating and initializing
// variable for simple date format.
SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy '\n\nand\n\nTime\n'HH:mm:ss z");
// on below line we are creating a variable
// for current date and time and calling a simple date format in it.
String currentDateAndTime = sdf.format(new Date());
// on below line we are setting current
// date and time to our text view.
currentTV.setText(currentDateAndTime);
}
}
Try it!!! hope this helps you