Get current time and date on Android

AndroidMobile DevelopmentApps/Applications

As per Oracle documentation, SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. In this example, we have imported simple date format class from java as shown below -

import java.text.SimpleDateFormat;
import java.util.Date;

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="match_parent">
   <TextView
      android:id="@+id/date"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:textSize="30sp"
      android:layout_marginBottom="36dp" />
</RelativeLayout>

In the above code, we have given text view, it going to print the current date on the window manager.

Step 3 − Add the following code to src/MainActivity.java

package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
   @TargetApi(Build.VERSION_CODES.O)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView=findViewById(R.id.date);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
      String currentDateandTime = sdf.format(new Date());
      textView.setText(currentDateandTime);
   }
}

In the above code we are calling SimpleDateFormat and from the simpledateformat, we are accessing the current date in the string. There are so many date format are available. For more reference Click here.

Step 4 − No need to change manifest.xml.

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

In the above example, it contains a current date and time.

Click here to download the project code

raja
Published on 25-Jan-2019 15:27:15
Advertisements