[英]Date parsing in Java using SimpleDateFormat
I want to parse a date in this format: "Wed Aug 26 2020 11:26:46 GMT+0200" into a date.我想将这种格式的日期解析为:“2020 年 8 月 26 日星期三 11:26:46 GMT+0200”。 But I don't know how to do it.但我不知道该怎么做。 I tried this:我试过这个:
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);
I am getting this error: Unparseable date: "Wed Aug 26 2020 11:26:46 GMT+0200".我收到此错误:无法解析的日期:“2020 年 8 月 26 日星期三 11:26:46 GMT+0200”。 Is my date format wrong?我的日期格式错误吗? And if so could somebody please point me in the right direction?如果可以的话,有人可以指出我正确的方向吗?
I suggest you stop using the outdated and error-prone java.util
date-time API and SimpleDateFormat
.我建议您停止使用过时且容易出错的java.util
date-time API 和SimpleDateFormat
。 Switch to the modern java.time
date-time API and the corresponding formatting API ( java.time.format
).切换到现代java.time
日期时间 API 和相应的格式化 API ( java.time.format
)。 Learn more about the modern date-time API from Trail: Date Time .从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);
}
}
Output:输出:
2020-08-26T11:26:46+02:00
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);
}
}
Output:输出:
Wed Aug 26 10:26:46 BST 2020
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.