首頁  >  文章  >  Java  >  如何使用Java中的Gson函式庫格式化日期?

如何使用Java中的Gson函式庫格式化日期?

WBOY
WBOY轉載
2023-08-19 12:45:23860瀏覽

如何使用Java中的Gson函式庫格式化日期?

##A

Gson 是一個 Java JSON 函式庫,由 Google 建立。透過使用Gson,我們可以產生JSON並將JSON轉換為java物件。我們可以透過建立 GsonBuilder 實例 並使用 create() 方法呼叫 來建立 Gson 實例。 GsonBuilder().setDateFormat()方法配置Gson根據提供的模式序列化Date物件。

Syntax

public GsonBuilder setDateFormat(java.lang.String pattern)

Example

的中文翻譯為:

範例

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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除