user1855656
user1855656

Reputation: 187

Android format a UTC datetime string into local format throws null error

hi I have the method below which takes the value of a UTC datetime string, format it to local display and return:

public static String convertDateStringUTCToLocal(String sourceUtcDateTimeString)
{
    SimpleDateFormat simpleDataFormat = new SimpleDateFormat();
    simpleDataFormat.setTimeZone(getCurrentTimeZone());
    String outputUTCDateTimeString = simpleDataFormat.parse(sourceUtcDateTimeString, new ParsePosition(0)).toString();

    return outputUTCDateTimeString;
}

public static TimeZone getCurrentTimeZone()
{
    Calendar calendar = Calendar.getInstance();
    TimeZone outputTimeZone = calendar.getTimeZone();

    return outputTimeZone;
}

I use getCurrentTimeZone() because user may change their local setting anytime and I don't want to hard code the format.

While debugging, the value of parameter sourceUtcDateTimeString is 'Mon Apr 15 13:54:00 GMT 2013', I found that 'simpleDataFormat.parse(sourceUtcDateTimeString, new ParsePosition(0))' gives me 'null', and 'simpleDataFormat.parse(sourceUtcDateTimeString, new ParsePosition(0)).toString()' throws error "java.lang.NullPointerException at toString()".

Looks like there is nothing at ParsePosition(0), but I am really new to Android dev, no idea why this is happening and how to get around it, could any one help out with a fix? I got stuck on this issue for hours.

thanks in advance.

Upvotes: 0

Views: 1546

Answers (1)

Thrakbad
Thrakbad

Reputation: 2738

It looks like the string you are trying to parse comes from a Date's toString() method, which gives the format dow mon dd hh:mm:ss zzz yyyy (see the javadoc). To parse that back to a Date you can either use Date parsed = new Date(Date.parse()), which is deprecated, or use a SimpleDateFormat with the format EEE MMM dd HH:mm:ss zzz yyyy (see SimpleDateFormat Documentation).

For example this code works for me:

public static String convertDateStringUTCToLocal(String sourceUtcDateTimeString)
{
    SimpleDateFormat simpleDataFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    // SimpleDateFormat already uses the default time zone, no need to set it again
    String outputUTCDateTimeString = simpleDataFormat.parse(sourceUtcDateTimeString, new ParsePosition(0)).toString();

    return outputUTCDateTimeString;
}

Depending on the rest of you application you should consider passing around any dates as a Date instance rather than using a String. You can then simply apply the right format any time you need to display the date to the user.

Upvotes: 1

Related Questions