
A Gson is a JSON library for Java, which is created by Google. By using Gson, we can generate JSON and convert JSON to java objects. We can create a Gson instance by creating a GsonBuilder instance and calling with the create() method. The GsonBuilder().setDateFormat() method configures Gson to serialize Date objects according to the pattern provided.
public GsonBuilder setDateFormat(java.lang.String pattern)
import java.util.Date;
import com.google.gson.*;
public class DateformatTest {
public static void main(String[] args) {
Employee emp = new Employee(115, "Surya", <strong>new Date()</strong>, 25000.00);
<strong>Gson </strong>gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String result = gson.toJson(emp);
System.out.println(result);
}
}
// Employee class<strong>
</strong>class Employee {
private int id;
private String name;
private Date doj;
private double salary;
public Employee(int id, String name, Date doj, double salary) {
this.id = id;
this.name = name;
this.doj = doj;
this.salary = salary;
}
}{"id":115,"name":"Surya","doj":"2019-09-26","salary":25000.0}以上就是如何使用Java中的Gson库格式化日期?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号