如何格式化2013-05-15T10:00:00-07:00到日期android

Soh*_*ziz 2 android date simpledateformat

我试图将日期字符串格式化为Date,然后从中获取月/日:

String strDate="2013-05-15T10:00:00-07:00";
SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss-z");

    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(strDate);
    } catch (ParseException e) {

        e.printStackTrace();
    }

 SimpleDateFormat sdfmonth = new SimpleDateFormat("MM/dd");
        String monthday= sdfmonth.format(convertedDate);
Run Code Online (Sandbox Code Playgroud)

但它返回我当前的月/日,即5/18。怎么了?

Sni*_*las 5

3件事:

  • 您的格式有误:2013-05-15T10:00:00-07:00没有任何意义,应该是2013-05-15T10:00:00-0700(结尾没有冒号,这是一个RFC 822中定义的时区。(请参阅有关Z 的文档)。
  • 如@blackbelt所述,将格式更改为yyyy-MM-dd'T'HH:mm:ssZ
  • 您会得到一个错误的日期,因为无论在解析过程中发生什么,您都要重新设置日期的格式。当且仅当解析有效时,才在try块中重新设置格式。

----------更新

    String strDate = "2013-05-15T10:00:00-0700";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(strDate);
        SimpleDateFormat sdfmonth = new SimpleDateFormat("MM/dd");
        String monthday = sdfmonth.format(convertedDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)