javaandroidepoch

How to correctly convert a timestring to a date object


I'm having trouble converting a time string into an accurate Date object representation

The server that I'm communicating with will provide a UTC time value such as this.

2013-01-02T05:32:02.8358602Z

When I try the following code, I end up with a millisecond count that is nearly 2hr15min ahead of the expected UTC.

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault());
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                   
Date date = inputFormat.parse("2013-01-02T05:32:02.8358602Z");

What am I doing wrong


Solution

  • Try this:

    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    Date d = format.parse(fileDate);
    

    Must specify the correct format in the SimpleDateFormat() constructor.

    Edited:

    public String getconvertdate1(String date)
    {
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
        Date parsed = null; // should not be initialized first else current date will be printed in case of a parse exception
        try
        {
            parsed = inputFormat.parse(date);
        }
        catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String outputText = outputFormat.format(parsed);
        return outputText;
    }
    

    And also try this format with my above method: EEE MMM dd HH:mm:ss zzz yyyy