In this post, I will show with example how to serialize and deserialize Date object.
Java provides “SimpleDateFormat” class to serialize and deserialize Date objects.
Below is an example
Main class
1 package datetime;
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 public class Example1 {
8 public static void main(String[] args) throws ParseException {
9 Date now = new Date();
10 SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
11 String serializedFormat = simpleDateFormat.format(now);
12 System.out.println(serializedFormat);
13
14 Date dateTime = simpleDateFormat.parse(serializedFormat);
15 }
16}
In the above code, at line 9 we create the “Date” object.
At line 10, We create an instance of “SimpleDateFormat”.
At line 11, we pass the “Date” instance “now” to SimpleDateFormat’s “format” method. This will return the date in String format, which is assigned to “serializedFormat” String variable.
At line 12, we print the String variable “serializedFormat”.
At line 14, we deserialize the String “serializedFormat” using the “parse” method of “SimpleDateFormat” class.
In the background, Java gets the default pattern based on default locale.
So if the default locale is English, India and below is the default pattern for that locale.
dd/MM/yy, h:mm a
The pattern is created using several symbols like in this example it is “d”, “M”, and “h” etc.
To understand this pattern, Java takes the help of “DateFormatSymbols” class, which will return the symbols associated to a specific locale.
Using all this information SimpleDateFormat understands the pattern and formats the Date object in that pattern.
When deserializing the Date, the String format should in the same default pattern otherwise it throws error.
In this way, we serialize and deserialize Date Object.