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?
好的,我有一个字符串,比如"Tue May 21 14:32:00 GMT 2012"我想把这个字符串转换成当地时间格式,2012年5月21日2:32 pm。我尝试了SimpleDateFormat(“MM dd, yyyyyyyhh: MM a”).parse(),但它抛出了一个异常。那么我该怎么做呢?
The exception is "unreported exception java.text.ParseException; must be caught or declared to be thrown."
异常是“未报告的异常java.text.ParseException;必须被抓住或宣布被扔。
in the line Date date = inputFormat.parse(inputText);
在行日期日期日期= inputFormat.parse(inputText)中;
The code I ran on TextMate:
我在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);
}
}
4 个解决方案
#1
21
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?
你能编译并运行正确的代码吗?
#2
3
The formatter you use to parse must be defined to the format you expect. Here is an example that works for the values you provided however you may need to change it depending on how some edge cases act for the input:
您用于解析的格式化程序必须定义为您期望的格式。以下是一个适用于您提供的值的示例,但是您可能需要根据某些边的情况对输入进行更改:
String date = "Tue May 21 14:32:00 GMT 2012";
DateFormat inputFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss zz yyy");
Date d = inputFormat.parse(date);
DateFormat outputFormat = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
System.out.println(outputFormat.format(d));
#3
1
The method SimpleDateFormat.parse throws a parse exception.
SimpleDateFormat方法。解析抛出一个解析异常。
The exception you're getting is telling you this...
你得到的例外是告诉你……
The exception is "unreported exception java.text.ParseException; must be caught or declared to be thrown."
异常是“未报告的异常java.text.ParseException;必须被抓住或宣布被扔。
Wrap the line that does the parsing with try-catch and you should be golden..
用try-catch包装完成解析的行,您应该是黄金。
Date d=null;
try{
d = inputFormat.parse(date);
catch(ParseException e){
// handle the error here....
}
R
R
#4
1
You are using troublesome old date-time classes now supplanted by the java.time classes.
您现在使用的是由java替代的恼人的旧日期时间类。时间类。
Wrong input data
Your first example string is incorrect, as the 21st is a Monday not a Tuesday. The second example string with 22nd is correct, and used in my example code below.
第一个示例字符串是不正确的,因为第21个是星期一而不是星期二。第22个示例字符串是正确的,在下面的示例代码中使用。
Using java.time
Avoid using this kind of format for textual representations of date-time values. In particular, never use the 3-4 letter abbreviation such as EST
or IST
seen in this kind of format, as they are not true time zones, not standardized, and not even unique(!). Specify a proper time zone name. In this particular case, java.time is able to translate that as GMT
as UTC, but other values may fail.
避免对日期-时间值的文本表示使用这种格式。特别是,千万不要使用3-4个字母的缩写,比如这种格式的EST或IST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)指定适当的时区名称。在本例中,是java。时间可以将其转换为GMT常量作为UTC,但是其他值可能会失败。
String input = "Tue May 22 14:52:00 GMT 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale ( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
System.out.println ( "zdt: " + zdt );
Dump to console. The toString
method generates a String in standard ISO 8601 format, extended by appending the name of the zone in brackets. These standard formats are a much better choice for when you need to serialize date-time values to text.
转储到控制台。toString方法生成标准ISO 8601格式的字符串,通过在括号中添加区域名称来扩展。当需要将日期-时间值序列化为文本时,这些标准格式是更好的选择。
System.out.println ( "zdt: " + zdt );
zdt: 2012-05-22T14:52Z[GMT]
zdt:2012 - 05 - 22 - t14:52z(格林尼治时间)
Generate String
You can generate a String to represent this value in any format you desire. Generally best to let java.time localize automatically using a Locale
and DateTimeFormatter
.
您可以生成一个字符串来以任何您想要的格式表示这个值。通常最好是让java。使用Locale和DateTimeFormatter自动本地化时间。
Your desired format uses a medium-length style for the date portion but a short-length style for the time-of-day portion. Fortunately the DateTimeFormatter
allows you to localize each portion separately, as seen here where we pass a pair of FormatStyle
objects.
您希望的格式为日期部分使用中长度样式,而为每日时间部分使用短长度样式。幸运的是,DateTimeFormatter允许您分别本地化每个部分,如这里所示,我们将传递一对格式样式对象。
Locale l = Locale.US; // Or Locale.CANADA_FRENCH, or Locale.ITALY, etc.
DateTimeFormatter fOutput = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM , FormatStyle.SHORT ).withLocale ( l );
String output = zdt.format ( fOutput );
Dump to console.
转储到控制台。
System.out.println ( "zdt: " + zdt + " | output: " + output );
zdt: 2012-05-22T14:52Z[GMT] | output: May 22, 2012 2:52 PM
输出:2012年5月22日下午2:52
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
java。time框架被构建到Java 8以及以后的版本中。这些类取代了旧的麻烦的日期时间类,如java.util。日期、.Calendar & java.text.SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出的许多例子和解释。
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
大部分java。time功能在three - backport中被反向移植到Java 6和7,并在ThreeTenABP中进一步适应Android(参见如何使用…)。
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。
#1
21
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?
你能编译并运行正确的代码吗?
#2
3
The formatter you use to parse must be defined to the format you expect. Here is an example that works for the values you provided however you may need to change it depending on how some edge cases act for the input:
您用于解析的格式化程序必须定义为您期望的格式。以下是一个适用于您提供的值的示例,但是您可能需要根据某些边的情况对输入进行更改:
String date = "Tue May 21 14:32:00 GMT 2012";
DateFormat inputFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss zz yyy");
Date d = inputFormat.parse(date);
DateFormat outputFormat = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
System.out.println(outputFormat.format(d));
#3
1
The method SimpleDateFormat.parse throws a parse exception.
SimpleDateFormat方法。解析抛出一个解析异常。
The exception you're getting is telling you this...
你得到的例外是告诉你……
The exception is "unreported exception java.text.ParseException; must be caught or declared to be thrown."
异常是“未报告的异常java.text.ParseException;必须被抓住或宣布被扔。
Wrap the line that does the parsing with try-catch and you should be golden..
用try-catch包装完成解析的行,您应该是黄金。
Date d=null;
try{
d = inputFormat.parse(date);
catch(ParseException e){
// handle the error here....
}
R
R
#4
1
You are using troublesome old date-time classes now supplanted by the java.time classes.
您现在使用的是由java替代的恼人的旧日期时间类。时间类。
Wrong input data
Your first example string is incorrect, as the 21st is a Monday not a Tuesday. The second example string with 22nd is correct, and used in my example code below.
第一个示例字符串是不正确的,因为第21个是星期一而不是星期二。第22个示例字符串是正确的,在下面的示例代码中使用。
Using java.time
Avoid using this kind of format for textual representations of date-time values. In particular, never use the 3-4 letter abbreviation such as EST
or IST
seen in this kind of format, as they are not true time zones, not standardized, and not even unique(!). Specify a proper time zone name. In this particular case, java.time is able to translate that as GMT
as UTC, but other values may fail.
避免对日期-时间值的文本表示使用这种格式。特别是,千万不要使用3-4个字母的缩写,比如这种格式的EST或IST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)指定适当的时区名称。在本例中,是java。时间可以将其转换为GMT常量作为UTC,但是其他值可能会失败。
String input = "Tue May 22 14:52:00 GMT 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale ( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
System.out.println ( "zdt: " + zdt );
Dump to console. The toString
method generates a String in standard ISO 8601 format, extended by appending the name of the zone in brackets. These standard formats are a much better choice for when you need to serialize date-time values to text.
转储到控制台。toString方法生成标准ISO 8601格式的字符串,通过在括号中添加区域名称来扩展。当需要将日期-时间值序列化为文本时,这些标准格式是更好的选择。
System.out.println ( "zdt: " + zdt );
zdt: 2012-05-22T14:52Z[GMT]
zdt:2012 - 05 - 22 - t14:52z(格林尼治时间)
Generate String
You can generate a String to represent this value in any format you desire. Generally best to let java.time localize automatically using a Locale
and DateTimeFormatter
.
您可以生成一个字符串来以任何您想要的格式表示这个值。通常最好是让java。使用Locale和DateTimeFormatter自动本地化时间。
Your desired format uses a medium-length style for the date portion but a short-length style for the time-of-day portion. Fortunately the DateTimeFormatter
allows you to localize each portion separately, as seen here where we pass a pair of FormatStyle
objects.
您希望的格式为日期部分使用中长度样式,而为每日时间部分使用短长度样式。幸运的是,DateTimeFormatter允许您分别本地化每个部分,如这里所示,我们将传递一对格式样式对象。
Locale l = Locale.US; // Or Locale.CANADA_FRENCH, or Locale.ITALY, etc.
DateTimeFormatter fOutput = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM , FormatStyle.SHORT ).withLocale ( l );
String output = zdt.format ( fOutput );
Dump to console.
转储到控制台。
System.out.println ( "zdt: " + zdt + " | output: " + output );
zdt: 2012-05-22T14:52Z[GMT] | output: May 22, 2012 2:52 PM
输出:2012年5月22日下午2:52
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
java。time框架被构建到Java 8以及以后的版本中。这些类取代了旧的麻烦的日期时间类,如java.util。日期、.Calendar & java.text.SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出的许多例子和解释。
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
大部分java。time功能在three - backport中被反向移植到Java 6和7,并在ThreeTenABP中进一步适应Android(参见如何使用…)。
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。