[英]Date parsing in Java using SimpleDateFormat
我想将这种格式的日期解析为:“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
date-time 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.