如何解决使用SimpleDateFormat在Java中进行日期解析
我想使用以下格式解析日期:“ 2020年8月26日星期三11:26:46 GMT + 0200”转换为日期。但是我不知道该怎么做。我尝试过:
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(split[0]); //error line
String formattedDate = formatter.format(date);
我遇到此错误:无法解析的日期:“ 2020年8月26日星期三11:26:46 GMT + 0200”。我的日期格式不正确吗?如果可以的话,请给我指出正确的方向?
解决方法
我建议您停止使用过时且容易出错的java.util
日期时间API和SimpleDateFormat
。切换到modern java.time
日期时间API和相应的格式API(java.time.format
)。从 Trail: Date Time 了解有关现代日期时间API的更多信息。
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Parse the given date-time string to OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,DateTimeFormatter.ofPattern("E MMM d u H:m:s zX",Locale.ENGLISH));
// Display OffsetDateTime
System.out.println(odt);
}
}
输出:
2020-08-26T11:26:46+02:00
使用旧版API:
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 {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Define the formatter
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z",Locale.ENGLISH);
// Parse the given date-time string to java.util.Date
Date date = parser.parse(dateTimeStr);
System.out.println(date);
}
}
输出:
Wed Aug 26 10:26:46 BST 2020
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。