更改字符串日期格式并在Android中设置为TextView?

Dev*_*per 10 android android-date android-dateutils

我想更改我的日期格式

String date ="29/07/13";
Run Code Online (Sandbox Code Playgroud)

但它显示*错误*Unparseable date:"29/07/2013"(偏移2)*我想以这种格式获取日期2013年7月29日.

这是我用来更改格式的代码.

tripDate = (TextView) findViewById(R.id.tripDate);
    SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy");
            try {
                oneWayTripDate = df.parse(date);
            } catch (ParseException e) {

                e.printStackTrace();
            }
            tripDate.setText(oneWayTripDate.toString());
Run Code Online (Sandbox Code Playgroud)

Ken*_*olf 31

试试这样:

String date ="29/07/13";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yy");
SimpleDateFormat output = new SimpleDateFormat("dd MMM yyyy");
try {
    oneWayTripDate = input.parse(date);                 // parse input 
    tripDate.setText(output.format(oneWayTripDate));    // format output
} catch (ParseException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

这是一个两步过程:首先需要将现有的String解析为Date对象.然后,您需要将Date对象格式化为新的String.


NIN*_*OOP 8

将格式字符串更改为MM/dd/yyyy,while parse()和use dd MMM yyyywhile format().

样品:

String str ="29/07/2013";
// parse the String "29/07/2013" to a java.util.Date object
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
// format the java.util.Date object to the desired format
String formattedDate = new SimpleDateFormat("dd MMM yyyy").format(date);
Run Code Online (Sandbox Code Playgroud)