Jan 22, 2013

Example of using SimpleDateFormat

The example demonstrate how to convert a Date object to string using a specified format, and convert back.

SimpleDateFormat

package com.example.androidsimpledateformat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView dateNow = (TextView)findViewById(R.id.datenow);
        TextView dateFormatted = (TextView)findViewById(R.id.dateformatted);
        TextView dateBack = (TextView)findViewById(R.id.dateback);
        
        //Initializes this Date instance to the current time.
        Date now = new Date();
        
        //Convert current time to String using specified format
        String format = "yyyy-MM-dd'T'HH:mm:ssZ";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.US);
        String formattedNow = simpleDateFormat.format(now);
        
        //Convert the string back to Date object
        Date dateConvertBack = null;
        try {
   dateConvertBack = simpleDateFormat.parse(formattedNow);
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        
        dateNow.setText(now.toString());
        dateFormatted.setText(formattedNow);
        dateBack.setText(dateConvertBack.toString());
    }
    
}


<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:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/datenow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/dateformatted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/dateback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


No comments:

Post a Comment

Infolinks In Text Ads