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

时间:2013-05-18 11:52:41

标签: 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);

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

2 个答案:

答案 0 :(得分:3)

3件事:

  • 您的格式有误:2013-05-15T10:00:00-07:00没有意义,应该是2013-05-15T10:00:00-0700(最后没有冒号,这是RFC 822中定义的时区。(查看关于Z的docs)。
  • 将您的格式更改为yyyy-MM-dd'T'HH:mm:ssZ,如@blackbelt所提及
  • 你得到一个糟糕的约会,因为你在解析期间重新格式化日期。当且仅当解析有效时,在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();
    }

答案 1 :(得分:1)

我不知道你的代码有什么问题。对我来说它抛出像这样的Unparseable异常。

java.text.ParseException: Unparseable date: "2013-05-15T10:00:00-07:00"

但以下方式效果很好。

String strDate="January 2, 2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy");
Date date = dateFormat.parse(strDate);
System.out.println(date.getMonth());

但是在Date中,根据deprecatedhttp://docs.oracle.com/Calender。尝试使用{{3}}代替日期。

我希望这会对你有所帮助。

相关问题