liuzhijun
liuzhijun

Reputation: 4469

SimpleDateFormat convert

SimpleDateFormat format = new SimpleDateFormat("GD_yyyyMMdd_HHmmss");
    System.out.println(format.format(new Date()));

I want a result like 'GD_20120604_164534'but the result is AD156_20120604_165315

how to set the param can return my willing result.thanks advance!

Upvotes: 0

Views: 872

Answers (5)

jonasr
jonasr

Reputation: 1876

SimpleDateFormat format = new SimpleDateFormat("'GD'_yyyyMMdd_HHmmss");
System.out.println(format.format(new Date()));

Use ' to escape your characters

Upvotes: 0

hmjd
hmjd

Reputation: 121961

G is an era designator and D represents day, as specified in the SimpleDateFormat reference, and:

Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote.

Change to:

SimpleDateFormat format = new SimpleDateFormat("'GD_'yyyyMMdd_HHmmss");

Upvotes: 4

juergen d
juergen d

Reputation: 204746

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
System.out.println("GD_" + format.format(new Date()));

Upvotes: 1

npinti
npinti

Reputation: 52185

According to the JavaDocs, G denotes the era and D denotes the day of the year.

One way of going round this and do what you want would be to do something like so:

String newDate = "GD_" + format.format(new Date());

Upvotes: 0

Michael Laffargue
Michael Laffargue

Reputation: 10294

This is because G and D are variables like yyyy:

G   Era designator  Text    AD
D   Day in year     Number  189

You should escape those two letter (I think with single quote)

Upvotes: 0

Related Questions