Java/Android - Convert a GMT time string to local time

Manto picture Manto · May 23, 2012 · Viewed 23.3k times · Source

Ok, so I have a string, say "Tue May 21 14:32:00 GMT 2012" I want to convert this string to local time in the format May 21, 2012 2:32 pm. I tried SimpleDateFormat("MM dd, yyyy hh:mm a").parse(), but it threw an exception. So what should I do?

The exception is "unreported exception java.text.ParseException; must be caught or declared to be thrown."

in the line Date date = inputFormat.parse(inputText);

The code I ran on TextMate:

public class test{
    public static void main(String arg[]) {
        String inputText = "Tue May 22 14:52:00 GMT 2012";
        SimpleDateFormat inputFormat = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
        inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        SimpleDateFormat out = new SimpleDateFormat("MMM dd, yyyy h:mm a");
        Date date = inputFormat.parse(inputText);
        String output = out.format(date);
       System.out.println(output);
    }
}

Answer

Jon Skeet picture Jon Skeet · May 23, 2012

The format string you provided for parsing doesn't correspond with the text format you've actually got. You need to parse first, then format. It looks like you want:

SimpleDateFormat inputFormat = new SimpleDateFormat(
    "EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy h:mm a");
// Adjust locale and zone appropriately

Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Here's the same code in the form of a short but complete program, with your sample input:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws ParseException {
        String inputText = "Tue May 21 14:32:00 GMT 2012";
        SimpleDateFormat inputFormat = new SimpleDateFormat
            ("EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
        inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

        SimpleDateFormat outputFormat =
            new SimpleDateFormat("MMM dd, yyyy h:mm a");
        // Adjust locale and zone appropriately
        Date date = inputFormat.parse(inputText);
        String outputText = outputFormat.format(date);
        System.out.println(outputText);
    }
}

Can you compile and run that exact code?