moatist
moatist

Reputation: 198

Convert date to friendly format using SimpleDateFormat

I am trying to format a date such as Mon Jul 28 00:00:00 CDT 2014 to something a bit more user friendly, such as Mon 6/28. What am I doing wrong?

Code:

        String date_string = "Mon Jul 28 00:00:00 CDT 2014";

        SimpleDateFormat inputFormatter = new SimpleDateFormat("ccc LLL F HH:mm:ss zzz yyyy"); //please notice the    capital M
        SimpleDateFormat outputFormatter = new SimpleDateFormat("ccc LLL/yyyy");

        try {
            Date date = inputFormatter.parse(date_string);
            String text = outputFormatter.format(date);
            System.out.println(text);
        } catch (ParseException e) {
            e.printStackTrace();
        }

When I use System.out.println to see what outputFormatter is set to, the result is: Sun Jan/2015

Upvotes: 0

Views: 1078

Answers (4)

Hariharan
Hariharan

Reputation: 24853

Try this..

Change this..

    SimpleDateFormat outputFormatter = new SimpleDateFormat("ccc LLL/yyyy");

to

    SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE M/dd");

EEE --> Mon

EEEE --> Monday

MM --> 06

M --> 6

dd --> 28

EDIT

    SimpleDateFormat inputFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

DEMO

http://ideone.com/c5rVT5

Upvotes: 3

Inder Sharma
Inder Sharma

Reputation: 15

SimpleDateFormat inputFormatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE MMM/yyyy");

This will print : Mon Jul/2014

If you use :

SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE L/d");

This will print : Mon 7/28

Upvotes: 0

Aniruddha
Aniruddha

Reputation: 4487

Try this

DateFormat df = new SimpleDateFormat("EEE M/dd");

Check this and this for more details.

Upvotes: 0

Phuong Nguyen
Phuong Nguyen

Reputation: 909

"Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number."

If you want the number version, use the shorter format in your output.

Upvotes: 0

Related Questions