Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem converting date format in Java

I have a string in the form MMM/dd/yyyy, ie. May/21/2010. Now I want to convert it to yyyyMMdd, ie. 20100521.

My code is:

public static void main(String[] args) {        
        ArrayList<String> dates = new ArrayList<String>();
        dates.add("Jan/13/2011");
        dates.add("Feb/03/2001");
        dates.add("Mar/19/2012");
        dates.add("Apr/20/2011");
        dates.add("May/21/2010");
        dates.add("Jun/23/2008");
        dates.add("Jul/12/2009");
        dates.add("Aug/14/2010");
        dates.add("Sep/01/2011");
        dates.add("Oct/07/2010");
        dates.add("Nov/05/2011");
        dates.add("Dec/30/2011");

        for(String s : dates) {
            System.out.println(transformPrevDate(s));
        }
    }

And the method to transform:

public String transformPrevDate(String datoe) {
        String[] splitter = datoe.split("/");
        String m = splitter[0].toUpperCase();
        String d = splitter[1];
        String y = splitter[2];

        DateFormat formatter = new SimpleDateFormat("MMM");
        DateFormat formatter2 = new SimpleDateFormat("MM");

        try {
            Date date = formatter.parse(m);
            m = formatter2.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String date = y + m + d;

        return date;
    }

The problem is that I get an Unparseable date exception, on May and Oct. I'm from Denmark and if I change it to danish "Maj" and "Okt" it succeeds. So what am I doing wrong here?

like image 952
Casper Avatar asked Apr 21 '26 01:04

Casper


1 Answers

Your transformDate method can be much simpler written like this:

DateFormat input = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
DateFormat output = new SimpleDateFormat("yyyyMMdd");
public String transformPrevDate(String datoe) throws ParseException {
    return output.format(input.parse(datoe));
}

You don't need to do your parsing yourself.

like image 153
Paŭlo Ebermann Avatar answered Apr 22 '26 13:04

Paŭlo Ebermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!