我的客户给我发送了一个日期,格式为“ 2019-11-22T16:16:31.0065786 + 00:00”。我收到以下错误:
java.text.ParseException:无法解析的日期:“ 2019-11-22T16:16:31.0065786 + 00:00”
我使用的日期格式是:
new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ")
.create();
请让我知道使用哪种格式。
此格式可以由DateTimeFormatter.ISO_ZONED_DATE_TIME的DateTimeFormatter
实例处理。它是Java Time
软件包的一部分,与1.8
版本一起发布。您应该使用ZonedDateTime
存储这样的值,但我们也可以将其转换为过时的Date
类。
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Date.class, new DateJsonDeserializer())
.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeJsonDeserializer())
.create();
System.out.println(gson.fromJson("{\"value\":\"2019-11-22T16:16:31.0065786+00:00\"}", DateValue.class));
}
}
class DateJsonDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ZonedDateTime zdt = ZonedDateTime.parse(json.getAsString());
return Date.from(zdt.toInstant());
}
}
class ZonedDateTimeJsonDeserializer implements JsonDeserializer<ZonedDateTime> {
@Override
public ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return ZonedDateTime.parse(json.getAsString());
}
}
class DateValue {
private ZonedDateTime value;
public ZonedDateTime getValue() {
return value;
}
public void setValue(ZonedDateTime value) {
this.value = value;
}
@Override
public String toString() {
return "DateValue{" +
"value=" + value +
'}';
}
}
以上代码打印:
DateValue{value=2019-11-22T16:16:31.006578600Z}
[在ZonedDateTime
类中将Date
更改为DateValue
时,它将根据您的时区打印此日期。
另请参见:
图案是"yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX"
。请检查https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Task {
public static void main(String[] args) {
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = null;
try {
date = simpleDateFormat.parse("2019-11-22T16:16:31.0065786+00:00");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}