Java/Android - 将GMT时间字符串转换为本地时间

Man*_*nto 9 java datetime android simpledateformat

好的,所以我有一个字符串,说"Tue May 21 14:32:00 GMT 2012"我想以2012年5月21日下午2:32的格式将此字符串转换为当地时间.我尝试了SimpleDateFormat("MM dd,yyyy hh:mm a").parse(),但它抛出异常.所以我该怎么做?

例外情况是"未报告的异常java.text.ParseException;必须被捕获或声明被抛出".

在线 Date date = inputFormat.parse(inputText);

我在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 22

您提供的用于解析的格式字符串与您实际获得的文本格式不符.您需要先解析,然后格式化.它看起来像你想要的:

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);
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个简短但完整的程序形式的相同代码,您的示例输入:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你能编译并运行那些确切的代码吗?