我想以以下格式解析日期:“ 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
。切换到现代 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
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句