我收到的电子邮件到达日期为“ 2020年7月14日星期二03:15:03 +0000(UTC)”,则需要将其转换为以下格式:“ 2020-02- 11 16:05:00 ”。谁能帮我实现此日期转换吗?
部分格式的输入日期格式,例如: EEE,d MMM yyyy HH:mm:ss
有人可以给我输入日期的确切日期格式吗?
我尝试过的事情:
try
{
String date_s = "Tue,14 Jul 2020 03: 15: 03 +0000 (UTC)";
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date tempDate=simpledateformat.parse(date_s);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Output date is = "+outputDateFormat.format(tempDate));
} catch (Exception ex)
{
ex.printStackTrace();
}
如下异常:
java.text.ParseException: Unparseable date: "Tue,14 Jul 2020 03: 15: 03 +0000 (UTC)"
at java.text.DateFormat.parse(DateFormat.java:366)
at JavaPackage.DateConvertion.main(DateConvertion.java:12)
等待您的答复。
注意:仅出于日期格式识别的目的,在转换后的日期上方随机给出。
答案 0 :(得分:2)
java.util
的日期时间API及其格式设置SimpleDateFormat
已过时且容易出错。我建议您应该完全停止使用它们,并切换到modern date-time API。
使用现代的日期时间API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Tue,14 Jul 2020 03: 15: 03 +0000 (UTC)";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("EEE,d MMM uuuu H: m: s Z '('z')'", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
System.out.println(dtfOutput.format(odt));
}
}
输出:
2020-07-14 03:15:03
通过 Trail: Date Time 了解有关现代日期时间API的更多信息。
如果您正在为Android项目工作,并且您的Android API级别仍不符合Java-8,请选中Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。
使用旧版API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "Tue,14 Jul 2020 03: 15: 03 +0000 (UTC)";
DateFormat sdfInput = new SimpleDateFormat("EEE,d MMM yyyy H: m: s Z '('z')'", Locale.ENGLISH);
Date date = sdfInput.parse(strDateTime);
DateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
sdfOutput.setTimeZone(sdfInput.getTimeZone());
System.out.println(sdfOutput.format(date));
}
}
输出:
2020-07-14 03:15:03
答案 1 :(得分:1)
字符串中的空格看起来很有趣。如果这些地方总是出现空格,请使用Arvind Kumar Avinash的答案。如果出现空格,可以通过将空格括在格式模式字符串中的方括号中来处理它们,从而:
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern(
"EEE,[ ]d MMM uuuu H[ ]:[ ]mm[ ]:[ ]ss xx[ ]'('z')'", Locale.ENGLISH);
String strDateTime = "Tue,14 Jul 2020 03: 15: 03 +0000 (UTC)";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
System.out.println(odt);
输出:
2020-07-14T03:15:03Z
格式模式字符串中的方括号包含可选部分,因此上述格式化程序将解析具有或不具有这些空格的字符串。
Oracle tutorial: Date Time解释了如何使用java.time。