如何使用 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