Serializing and De-Serializing Date object to and from a custom pattern

In this post under Java, I will show with example how to serialize and de-serialize Date object using a custom pattern.

In the previous post, we used “SimpleDateFormat” class to serialize and de-serialize Date object using a pattern obtained based on system default locale.

This pattern was figured out by Java and was not provided by us.

In our new example we will provide our own pattern.

To create a pattern, we need to use certain symbols that can be understood by “SimpleDateFormat” class.

These symbols are obtained by using the “DateFormatSymbols” class as shown below


DateFormatSymbols.getInstance(locale)

I being in India, the date format symbols will be as shown below


GyMdkHmsSEDFwWahKzZ

Which is obtained using the below code


Locale locale = new Locale("en", "INDIA");
System.out.println(DateFormatSymbols.getInstance(locale).getLocalPatternChars());

Now lets come up with our custom pattern which is as shown below


'Date: 'd-D/M/yyyy,' - Time: 'H:m

Where ‘d’ –> Day in month, ‘D’ –> Day in year, ‘M’ –> month, ‘y’ –> year, ‘H’ –> hour (0-24), and ‘m’ –> minute.

In the above pattern, text enclosed within single quotes are not considered as symbols but just text.

Below is the complete Java code for our example

Main Class


1  package datetime;
2  
3  import java.text.DateFormatSymbols;
4  import java.text.ParseException;
5  import java.text.SimpleDateFormat;
6  import java.util.Date;
7  import java.util.Locale;
8  
9  public class Example2 {
10     public static void main(String[] args) throws ParseException {
11         Date now = new Date();
12         Locale locale = new Locale("en", "INDIA");
13         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("'Date: 'd-D/M/yyyy,' - Time: 'H:m", DateFormatSymbols.getInstance(locale));
14         String serializedFormat = simpleDateFormat.format(now);
15         System.out.println(serializedFormat);
16         Date dateTime = simpleDateFormat.parse(serializedFormat);
17     }
18 }

In the above code, at line 11, we create a new “Date” instance which represents the current date and time.

At line 12, we create a new “Locale” instance for India country and English language.

At line 13, we create an instance of “SimpleDateFormat” giving the custom pattern and DateFormatSymbols for India locale as constructor arguments.

In other words we are telling “SimpleDateFormat” instance that this is our pattern and to understand our pattern use these DateFormatSymbols.

At line 14, we call “format” method on “SimpleDateFormat” instance and the result is stored in String variable “serializedFormat”, which is printed at line 15.

At line 16, the same “SimpleDateFormat” instance can be used to De-Serialize a date stored as String in our custom pattern to create Date object.

In this way we can serialize or de-serialize Date object using custom pattern.

Output


Date: 21-21/1/2023, - Time: 10:49

Leave a Reply