Android : date format in a String

2019-04-18 16:30发布

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

5条回答
Deceive 欺骗
2楼-- · 2019-04-18 16:54

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

查看更多
家丑人穷心不美
3楼-- · 2019-04-18 17:01
 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"

查看更多
太酷不给撩
4楼-- · 2019-04-18 17:02

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));
查看更多
太酷不给撩
5楼-- · 2019-04-18 17:02

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.

查看更多
在下西门庆
6楼-- · 2019-04-18 17:11

here is a simple way to convert Date to String :

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

String strDt = simpleDate.format(dt);

查看更多
登录 后发表回答