Aug 4, 2014

Display date/time in various format with SimpleDateFormat

Examples of using java.text.SimpleDateFormat:


package com.example.androidtime;

import java.text.SimpleDateFormat;
import java.util.Calendar;

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


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView cal = (TextView)findViewById(R.id.cal);
        
        Calendar calendar = Calendar.getInstance(); 
        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat format2 = new SimpleDateFormat("yy/MM/dd");
        SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat format4 = new SimpleDateFormat("yyyy MMM dd (EEE)");
        SimpleDateFormat format5 = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat format6 = new SimpleDateFormat("HH:mm");

        cal.setText(
         format1.format(calendar.getTime()) + "\n" +
         format2.format(calendar.getTime()) + "\n" +
         format3.format(calendar.getTime()) + "\n" +
         format4.format(calendar.getTime()) + "\n" +
         format5.format(calendar.getTime()) + "\n" +
         format6.format(calendar.getTime())
         );

    }

}

<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidtime.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com" />
    <TextView
        android:id="@+id/cal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp" />

</LinearLayout>

Related: Display formatted date/time using String.format().

No comments:

Post a Comment

Infolinks In Text Ads