display current date and time in android

watch_later Friday, July 29, 2016
Hi,Today we learn about how to get current date and time in android using SimpleDateFormat and Date.

we can get date or time based on our requirement
Create a Project:

Create following layout file

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/datetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textColor="@color/material_blue_grey_900"
        android:layout_centerInParent="true"/>


</RelativeLayout>



MainActivity.java


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

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView datetext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
datetext=(TextView)findViewById(R.id.datetext);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss");
       Date curDate = new Date();
       String stringDate = sdf.format(curDate);
       datetext.setText(stringDate);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.forblog"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
     
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>


Finally, Run your application

Output:




sentiment_satisfied Emoticon