1. 程式人生 > >Google Gson 格式化日期時間

Google Gson 格式化日期時間

本文內容大多基於官方文件和網上前輩經驗總結,經過個人實踐加以整理積累,僅供參考。

示例 1

@Test
public void test() throws IOException {
    Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd")
        .create();
    System.out.println(gson.toJson(new Date()));
}

執行結果:
這裡寫圖片描述

示例 2

@Test
public void test() throws IOException {
    Gson gson = new
GsonBuilder() .setDateFormat("yyyy-MM-dd hh:mm:ss") .create(); System.out.println(gson.toJson(new Date())); }

執行結果:
這裡寫圖片描述

示例 3

@Test
public void test() throws IOException {
    Gson gson = new GsonBuilder()
        .setDateFormat("MM-dd-yyyy hh:mm")
        .create();
    System.out.println(gson.toJson(new
Date())); }

執行結果:
這裡寫圖片描述