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
Where is the activity_main.xml?