views:

427

answers:

1

Hi:

I have a date string and I wang to parse it to normal date use the java Date API,the following is my code:

    public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    String pattern="yyyy-MM-ddThh:mm:ssZ";
    SimpleDateFormat sdf=new SimpleDateFormat(pattern);
    try {
        Date d=sdf.parse(date);
        System.out.println(d.getYear());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

However I got a exception:java.lang.IllegalArgumentException: Illegal pattern character 'T'

So I wonder if i have to split the string and parse it manually?

BTW, I have tried to add a single quote character on either side of the T:

String pattern="yyyy-MM-dd'T'hh:mm:ssZ";

It also does not work.

+1  A: 

This works, note the single quotes around the T and that I removed the Z from both the date and the pattern, since you don't have a valid timezone offset in your example that is why it is failing.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SDF
{
    public static void main(final String[] args)
    {
        final String date = "2010-10-02T12:23:23";
        final String pattern = "yyyy-MM-dd'T'hh:mm:ss";
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try
        {
            Date d = sdf.parse(date);
            System.out.println(d);
        } 
        catch (ParseException e)
        {
            e.printStackTrace();
        }

    }
}

and here is what it output

Sat Oct 02 00:23:23 EDT 2010

If you really have timezone information in your date you need to use the proper Z/z, but your date has a actual Z in it not a valid timezone offset. Like the following:

final String date = "2010-10-02T12:23:23+0500";
final String pattern = "yyyy-MM-dd'T'hh:mm:ssZ";

and here is what I get as output with EST/+0500 as my timezone

Fri Oct 01 15:23:23 EDT 2010
fuzzy lollipop
ok,thanks.Did you mean that even if SimpleDateFormat can parse some string to a Date,the stirng to be parsed can not be any value,it should also be according to some schema?That's to mean the string "2010-10-02T12:23:23Z" can never be parsed unless I remove the last character "Z" ?
hguser
on the last `Z` in the `date` was not the problem, it was the `Z` in the pattern, that tells it to parse the timecode offset. `Z` in the data is not a valid timecode offset. So do I get the checkmark? The `pattern` is the schema, it has to match that pattern. `Z` is the pattern match for the timezone information.
fuzzy lollipop