的Java / Android的 - 将一个GMT时间字符串为本地时间 [英] Java/Android - Convert a GMT time string to local time
问题描述
好了,我有一个字符串,说:周二5月21日十四时32分00秒格林尼治标准时间2012我想这个字符串转换为本地时间格式2012年5月21日下午2时32分。我试过的SimpleDateFormat(MM DD,YYYY HH:MM一)。解析(),但它引发了异常。所以,我应该怎么办?
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?
唯一的例外是没有报告异常java.text.ParseException;必须捕获或声明抛出
The exception is "unreported exception java.text.ParseException; must be caught or declared to be thrown."
在该行日期日期= inputFormat.parse(inputText的)
in the line Date date = inputFormat.parse(inputText)
在code我跑TextMate的:
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);
}
}
推荐答案
你提供的格式字符串的解析</ em>的不与你实际上已经得到了文本格式一致。你需要先解析,然后格式化。它看起来像你想要的:
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);
编辑:这是同样的code在很短,但完整的程序的形式,与样品输入:
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);
}
}
您可以编译和运行的的确切code 的?
Can you compile and run that exact code?
这篇关于的Java / Android的 - 将一个GMT时间字符串为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!