如何使用 Java 中的 Gson 库来格式化日期?
Gson 是一个针对 Java 的 JSON 库,由谷歌创建。通过使用 Gson,我们可以生成 JSON 并将 JSON 转换为 Java 对象。我们可以通过创建GsonBuilder 实例 并用 create() 方法进行调用来创建一个 Gson 实例。GsonBuilder().setDateFormat() 方法将 Gson 配置为根据提供的模式来序列化 Date 对象。
语法
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", new Date(), 25000.00);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String result = gson.toJson(emp);
System.out.println(result);
}
}
// Employee class
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}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP