开发者

How to apply applyPattern for SimpleDateFormat in java?

开发者 https://www.devze.com 2023-04-11 02:26 出处:网络
I am trying to add a new pattern to the date display but I am not getting the result that I am expecting:

I am trying to add a new pattern to the date display but I am not getting the result that I am expecting:

Here is my code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");
    sdf.applyPattern("yyyy-MM-dd");
     Date date_out = null;
    try {
        date_out = sdf.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catc开发者_运维问答h block
        e.printStackTrace();
    }

((TextView) view.findViewById(R.id.date)).setText(date_out.toString());

I want the output to look something like this: 03 Oct 2011

However this is the output tat I am getting: Oct 03 00:00:00 GMT+ 11:00 2011

How do I reach the desired output?

EDIT: I solved this code by adding this line:

sdf.format(date_out);

instead of setText()


Date.toString(); does always format your String that way. You should a SimpleDateFormat to format the Date object to the String you want.

The JavaDoc of the Date.toString(); method says:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy


You have to use two SimpleDateFormat objects. One for parsing the input and an other one for formatting the parsed Date object to String.

final String inputDate = "2011-05-08T11:12:13.0123";
final SimpleDateFormat inputParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");

Date date_out = null;
try {
    date_out = inputParser.parse(inputDate);
} catch (final ParseException e) {
    e.printStackTrace();
}

final SimpleDateFormat outputFormatter = 
    new SimpleDateFormat("dd MMM yyyy", Locale.US);

final String result = outputFormatter.format(date_out);
System.out.println(result);

Output:

08 May 2011


The Date.toString() method formats the string like that (check the api documentation).

You do not actually need to use applyFormat(...) in this case. You want to parse one format and output it in another format.

To parse the date (given the string: 2011-10-03") use can use the format"yyyy-MM-dd"and when you output theDateyou want to use"dd MMM yyyy"`:

public static void main(String[] args) throws ParseException {

    SimpleDateFormat inputFormat  = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy MMM dd");

    Date parsedDate = inputFormat.parse("2011-10-05");

    System.out.println(outputFormat.format(parsedDate));
}

Outputs (on US locale):

2011 Oct 05


Read below document :-

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

hope help u above link.

0

精彩评论

暂无评论...
验证码 换一张
取 消