Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จัดรูปแบบวันที่ (Date Format) ด้วย Gson Library ใน Java

Gson เป็น JSON Library สำหรับ Java สร้างโดย Google ใช้สร้าง JSON และแปลง JSON เป็น Java Object สร้าง Gson Instance ผ่าน GsonBuilder เรียก create() เมธอด GsonBuilder().setDateFormat() กำหนดให้ Gson Serialize Date Objects ตาม Pattern ที่กำหนด

Syntax

public GsonBuilder setDateFormat(String pattern)

ตัวอย่าง: Format Date ด้วย Gson

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}

Pattern ตัวอย่าง:

  • yyyy-MM-dd → 2019-09-26
  • dd/MM/yyyy → 26/09/2019
  • yyyy-MM-dd HH:mm:ss → 2019-09-26 14:30:00
  • EEE, dd MMM yyyy HH:mm:ss zzz → RFC 1123 Format

หมายเหตุ: ใช้ SimpleDateFormat Patterns เหมือนกัน รองรับ java.util.Date และ java.sql.Date