A blog for technology, SEO tips, website development and open source programming.

SimpleDateFormat example on Android

1 7,172

android_alarm

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

MainActivity.java

package com.panayiotisgeorgiou.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());
}

}

Activity_main.xml

 

 

1 Comment
  1. Ward Pieters says

    Where is the activity_main.xml?

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More