如何使用Gson解析"2018-04-09T09:00:00+02:00"格式的日期字符串?
2018-04-09T09:00:00+02:00 Format Hey there, let's get this date parsing issue sorted out! The problem here is that your SimpleDateFormat pattern doesn't match the actual format of the date string you're trying to parse. Let's break down what's wrong and how to fix it.
What's Causing the Exception?
Your current pattern is yyyy-MM-dd'T'HH:mm:ss'Z' — notice the single quotes around Z? That tells SimpleDateFormat to treat Z as a literal character, but your input date uses a time zone offset (+02:00) instead of the UTC indicator Z. The parser can't reconcile this mismatch, hence the ParseException that bubbles up to Gson's JsonSyntaxException.
Solution 1: Fix the SimpleDateFormat Pattern
Replace the literal 'Z' with XXX, which is the pattern for time zone offsets formatted with a colon (like +02:00). Here's how to update your Gson configuration:
// Create a Gson instance with the correct date format Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US) .create();
If you're using a custom DefaultDateTypeAdapter, update the SimpleDateFormat like this:
DefaultDateTypeAdapter dateAdapter = new DefaultDateTypeAdapter( new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US) ); Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, dateAdapter) .create();
This pattern will correctly parse dates with offsets like +02:00, +00:00, or -05:00.
Solution 2: Use Java 8+ Time API (Recommended)
The old Date and SimpleDateFormat classes are thread-unsafe and outdated. For a more robust solution, switch to Java 8's java.time API (like OffsetDateTime, which perfectly matches your input format).
First, if you're using Maven, add the gson-java8 dependency to handle Java 8 time types:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson-java8</artifactId> <version>2.10.1</version> <!-- Use the latest available version --> </dependency>
Then configure Gson to use the Java Time module:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.module.Adapters; // Register the Java Time module to handle OffsetDateTime and other java.time types Gson gson = new GsonBuilder() .registerModule(Adapters.JAVA_TIME) .create();
Now you can use OffsetDateTime directly in your model classes:
public class MyModel { private OffsetDateTime timestamp; // Getters and setters }
Gson will automatically parse the 2018-04-09T09:00:00+02:00 string into an OffsetDateTime instance without any custom format strings needed.
Either of these solutions should resolve your parsing exceptions. The Java 8 time approach is the better long-term choice due to its safety and flexibility.
内容的提问来源于stack exchange,提问作者Alessandro C

