Android format date

In Android, to format a date and time you can use DateFormat class. Typically, a DateFormat object is not created using its constructor. Instead, you will use the getDateInstance(int style) and getTimeInstance(int style) methods to get an instance of DateFormat to format a date and time. The DateFormat class is able to convert a date to string and vice-versa. The format() method turns the data to string and the parse() method turns the string to date.

Now to have a workable example application that formats a date, create a new Android project. Then modify the activity_main.xml file to add an id attribute to the TextView so that you can refer to it later in code.

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

   <TextView
     android:id="@+id/txtdate"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textSize="20sp" />

</RelativeLayout>



In the onCreate() method of the MainActivity class (in MainActivity.java file), write the code below. This code formats the current date in a long style and displays the result on the TextView.
DateFormat df=DateFormat.getDateInstance(DateFormat.LONG);
TextView tv=(TextView)findViewById(R.id.txtdate);
Calendar calendar=Calendar.getInstance();
tv.setText(df.format(calendar.getTime()));

If you want to apply your own pattern when you format a date, you will use the SimpleDateFormat class. It is a sub-class of the DateFormat class. For example, the following code formats the current date in the form of "dd-MM-yyyy". The dd part is two-digit date; The MM part is two-digit month; and the yyyy part is four-digit year.

Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = df.format(c.getTime());

Android-format-date

Posted by: Dara | post date: 08-26-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.