Get system date/time and display in formatted form


MainActivity.java
package com.blogspot.android_er.androiddatetime;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

TextView tvNow, tvNowFormatted1, tvNowFormatted2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNow = (TextView)findViewById(R.id.now);
tvNowFormatted1 = (TextView)findViewById(R.id.nowformatted1);
tvNowFormatted2 = (TextView)findViewById(R.id.nowformatted2);

Date now = new Date();
tvNow.setText(now.toString());

String nowFormatted1 = DateFormat.getDateTimeInstance().format(now);
tvNowFormatted1.setText(nowFormatted1);

String nowFormatted2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss").format(now);
tvNowFormatted2.setText(nowFormatted2);
}
}



activity_main.xml

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androiddatetime.MainActivity">

android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold"/>

android:id="@+id/now"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="28dp"/>

android:id="@+id/nowformatted1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:textStyle="bold"
android:textSize="28dp"/>
android:id="@+id/nowformatted2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#0000FF"
android:textStyle="italic"
android:textSize="28dp"/>




Reference:
java.util.Date
java.text.DateFormat
java.text.SimpleDateFormat




Popular posts from this blog

OnePlus Releases OxygenOS 4.5 OTA For OnePlus 3 and OnePlus 3T

Report: Incredibly Accurate GPS Chips are Coming to Smartphones Next Year

Black Friday saw the lowest price yet for the Roomba j7 from iRobot.