2

I am trying to format the date string to Date, and then get the month/day from it:

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

but it returns me current month/day i.e 5/18. Whats wrong?

SohailAziz
  • 8,034
  • 6
  • 41
  • 43

2 Answers2

5

3 things :

  • There is a mistake in your format : 2013-05-15T10:00:00-07:00 has no meaning, it should be 2013-05-15T10:00:00-0700 (with no colon at the end, this is a timezone defined in RFC 822. (Look at the docs about Z).
  • Change your format to yyyy-MM-dd'T'HH:mm:ssZ as mentionned by @blackbelt
  • you get a bad date because you re-format your date whatever happens during parsing. Re-format in your try block, if and only if parsing worked.

----------Update

    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();
    }
Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • `2013-05-15T10:00:00-0700` this string also thows me Unparseable exception friend. – Gunaseelan May 18 '13 at 12:34
  • I tried this with latest android sdk. It worked. I aspected It will not, but Actually It worked (with yyyy-MM-dd'T'HH:mm:ssZ). Any clues? – Blackbelt May 18 '13 at 12:41
  • Sorry friend this one runs perfectly. Itried with `new SimpleDateFormat( "MMMM d, yyyy")`. That is problem I think. – Gunaseelan May 18 '13 at 12:46
2

I don't know what is wrong in your code. for me it throws Unparseable exception like this.

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

But the following way works well.

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

But in java Date is deprecated as per http://docs.oracle.com/ . Try to use Calender instead of Date.

I hope this will help you.

Community
  • 1
  • 1
Gunaseelan
  • 14,415
  • 11
  • 80
  • 128