简体   繁体   English

Android使用SimpleDateFormat将字符串解析为日期

[英]Android parsing String to Date with SimpleDateFormat

I have String dateOrder= '2014-09-28' , i want to change format with SimpleDateFormat. 我有String dateOrder ='2014-09-28',我想使用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 . 您可以将其用于parse Then you need another SimpleDateFormat("dd/MM/yy") for formatting the new version. 然后,您需要另一个SimpleDateFormat("dd/MM/yy")来格式化新版本。

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. 因此,您不仅需要创建一个SimpleDateFormat实例,还需要两种具有不同模式的模板:一种用于解析,另一种用于格式化。

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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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