Android : date format in a String

60,848

Solution 1

here is a simple way to convert Date to String :

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

String strDt = simpleDate.format(dt);

Solution 2

 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"

Solution 3

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

Solution 4

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

Share:
60,848
HerrM
Author by

HerrM

Updated on July 22, 2022

Comments

  • HerrM
    HerrM almost 2 years

    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(mYear).append(".")
       .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.

    EDIT :

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

    I replaced this :

    dateRappDB = (new StringBuilder()
      .append(mYear).append(".")
      .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 :)