我有以下日期:2011-08-12T20:17:46.384Z。这是什么格式?我试图用Java 1.4通过DateFormat.getDateInstance().parse(dateStr)来解析它
java.text.ParseException: Unparseable date: "2011-08-12T20:17:46.384Z"
我认为我应该使用SimpleDateFormat进行解析,但我必须首先知道格式字符串。到目前为止,我只有yyyy-MM-dd,因为我不知道T在这个字符串中是什么意思——与时区相关的东西?这个日期字符串来自文件CMIS下载历史媒体类型上显示的lccmis: downloaddon标记。
除了第一个答案,还有其他方法来分析它。解析方法:
(1)如果你想获取日期和时间的信息,你可以将它解析为一个ZonedDatetime(自Java 8以来)或date(旧)对象:
// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);
or
// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);
Date myDate = df.parse("2011-08-12T20:17:46.384Z");
(2)如果你不关心日期和时间,只想把信息当作以纳秒为单位的时刻,那么你可以使用Instant:
// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");
如果你正在寻找Android的解决方案,你可以使用下面的代码从时间戳字符串中获取纪元秒。
public static long timestampToEpochSeconds(String srcTimestamp) {
long epoch = 0;
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Instant instant = Instant.parse(srcTimestamp);
epoch = instant.getEpochSecond();
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(srcTimestamp);
if (date != null) {
epoch = date.getTime() / 1000;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return epoch;
}
样品输入:2019-10-15T05:51:31.537979Z
样本输出:1571128673
该技术将java.util.Date转换为UTC格式(或任何其他格式),然后再转换回来。
像这样定义一个类:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class UtcUtility {
public static DateTimeFormatter UTC = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();
public static Date parse(DateTimeFormatter dateTimeFormatter, String date) {
return dateTimeFormatter.parseDateTime(date).toDate();
}
public static String format(DateTimeFormatter dateTimeFormatter, Date date) {
return format(dateTimeFormatter, date.getTime());
}
private static String format(DateTimeFormatter dateTimeFormatter, long timeInMillis) {
DateTime dateTime = new DateTime(timeInMillis);
String formattedString = dateTimeFormatter.print(dateTime);
return formattedString;
}
}
然后这样使用它:
Date date = format(UTC, "2020-04-19T00:30:07.000Z")
or
String date = parse(UTC, new Date())
如果需要,还可以定义其他日期格式(不仅仅是UTC)