首页  >  文章  >  Java  >  如何使用Java中的Gson库格式化日期?

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

WBOY
WBOY转载
2023-08-19 12:45:23861浏览

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

A Gson 是一个用于 Java 的 JSON 库,由 Google 创建。通过使用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", <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删除