简体   繁体   中英

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

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

"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.

Try this

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

Check this and this for more details.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM