我正在尝试解析带有日期的字符串,以将其转换为日期格式。字符串采用以下格式。
[2020年1月9日,星期四; 04:31:59 PM(GMT +05:30)
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM dd yyyy; hh:mm:ss a",Locale.ENGLISH);
for(int i=0 ; i <jArr.length() ; i++){
String tempDate = jArr.get(i).toString();
dateList.add(tempDate);
}
try{
Date d1 = sdf3.parse(dateList.get(0));
} catch (Exception e) {
e.printStackTrace();
}
注意:此功能适用于android版本> 6。
要获得所需的格式,您必须使用如下所示的SimpleDateFormat
:
String dateString = "Thursday, Jan 09 2020; 04:31:59 PM (GMT +05:30)";
SimpleDateFormat sourceFormat = new SimpleDateFormat("EEE, MMM dd yyyy; hh:mm:ss a",Locale.ENGLISH);
try{
Date d1 = sourceFormat.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yy; hh:mm:ss a", Locale.ENGLISH)
String desiredString = targetFormat.format(d1);
//desiredString is now "09/01/20; 04:31:59 PM"
在SimpleDateFormat的参数中尝试使用此EPOCH_FORMAT:
String formatter = "EE MMM dd HH:mm:ss z yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(formatter,Locale.US);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"EEEE, MMM dd uuuu; hh:mm:ss a '(GMT' xxx')'", Locale.ENGLISH);
String tempDate = "Thursday, Jan 09 2020; 04:31:59 PM (GMT +05:30)";
OffsetDateTime odt = OffsetDateTime.parse(tempDate, formatter);
System.out.println(odt);
此代码段的输出是:
2020-01-09T16:31:59 + 05:30
为了获得正确的时间,您需要分析字符串中的GMT偏移量。
我使用的是Java.time,这是现代的Java日期和时间API,因为SimpleDateFormat
和Date
的设计欠佳,而且已经过时,尤其是前者特别麻烦。而且因为java.time更好用。
java.time在较新和较旧的Android设备上均可正常运行。它只需要至少Java 6。
org.threeten.bp
导入日期和时间类。java.time
。java.time
到Java 6和7的反向端口(JSR-310为ThreeTen)。