简体   繁体   中英

Android parsing String to Date with SimpleDateFormat

I have String dateOrder= '2014-09-28' , i want to change format with SimpleDateFormat. but this is cannot formated.. how to solve ?
this my code

SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
        String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
        try {
            Date d = date.parse(dateOrder);
            dateOrder = date.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Try changing the first line to

SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");

You can use this for the parse . Then you need another SimpleDateFormat("dd/MM/yy") for formatting the new version.

The key point is that the parsing needs to be done with one pattern, and the formatting needs to be done with another. So rather than just creating one SimpleDateFormat instance, you need two, with different patterns: one for parsing, and one for formatting.

I believe you want something like this:

    //first create an object that will parse your date as you have it ie 2014-09-28
    SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
    String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
    try {
        Date d = date.parse(dateOrder);
        //then use a different object to format the date as you want it ie 9/28/2014
        dateOrder = new SimpleDateFormat("dd/MM/yy").format(d);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

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