java – Android : date format in a String-ThrowExceptions

Exception or error:

I have a problem to sort date because of the format of these dates.

I obtain the date :

final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

And I build a String with these values.

dateRappDB = (new StringBuilder()
   .append(mMonth + 1).append(".")
   .append(mDay).append(" ")).toString();

The problem is that if the month is for example February, mMonth value is 2. So dates with months like October (10) comes before in my list.

What I need is that month and day are formated like MM and dd. But I don’t know how to do it in my case.


I solved the problem by using a DateFormat like said above.

I replaced this :

dateRappDB = (new StringBuilder()
  .append(mMonth + 1).append(".")
  .append(mDay).append(" ")).toString();

By this :

Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();

And it works.
Thanks to all of you for your help 🙂

How to solve:

here is a simple way to convert Date to String :

SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");

String strDt = simpleDate.format(dt);


 Calendar calendar = Calendar.getInstance();
 Date now = calendar.getTime();   
 String timestamp = simpleDateFormat.format(now);

These might come in handy

SimpleDateFormat simpleDateFormat = 
   new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");

this format is equal to –> “2016-01-01T09:30:00.000000+01:00”

SimpleDateFormat simpleDateFormat = 
   new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");

this format is equal to –> “2016-06-01T09:30:00+01:00”


here is the example for date format

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();

System.out.println("format 1 " + sdf.format(date));

sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));


You need to sort dates, not strings. Also, have you heared about DateFormat? It makes all that appends for you.


If I understand your issue, you create a list of dates and since they’re strings, they get arranged in a dictionary-order number-wise, which means you get october before february (10 before 2).

If I were you, I would store my results in a container where I control the insertion point (like an array list) or where I can control the sorting algorithm.

Leave a Reply

Your email address will not be published. Required fields are marked *