
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Format Date Using Gson Library in Java
Gson is a JSON for Java, which is developed by Google. We can format a date using the Gson library in Java. The Gson library provides a GsonBuilder class that allows us to create a Gson instance with custom settings.
We call the create() method of the GsonBuilder class to create an instance of the Gson class. Then we use the method setDateFormat() to configure Gson to serialize Date objects according to the pattern provided. In order to use the Gson library, we need to add it to our project.
If you are using Maven, add this to your pom.xml file -
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
And, if you are not using Maven, add the Gson jar file to your project. You can download the jar file from here.
Formatting a date using the Gson library in Java
To format a date using the Gson library in Java, follow these steps:
- First, import the Gson library.
- Then create a class Person with fields for name and date of birth.
- Then create a GsonBuilder instance.
- Then call the setDateFormat() method of the GsonBuilder instance to set the date format.
- Now create a Gson instance using the create() method of the GsonBuilder.
- Then create a Person object.
- Then convert the Person object to a JSON string using the toJson() method of the Gson.
- Finally, print the JSON string.
Example
Following is the code to format a date using the Gson library in Java:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.text.SimpleDateFormat; import java.util.Date; public class FormatDateExample { public static void main(String[] args) { // Create a GsonBuilder instance GsonBuilder gsonBuilder = new GsonBuilder(); // Set the date format gsonBuilder.setDateFormat("yyyy-MM-dd"); // Create a Gson instance Gson gson = gsonBuilder.create(); // Create a Person object Person person = new Person("Ansh", new Date()); // Convert the Person object to JSON string String jsonString = gson.toJson(person); System.out.println(jsonString); } }
Following is the output of the above code:
{"name":"Ansh","dateOfBirth":"2023-10-25"}