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

     android:textSize="20sp" />


In the onCreate() method of the MainActivity class (in 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(;
Calendar calendar=Calendar.getInstance();

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());


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.