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

วิธีดึงวันที่ปัจจุบันใน Java


มีหลายวิธีดึงวันที่ปัจจุบัน (Current Date) ใน Java

วิธีที่ 1: ใช้ Date + SimpleDateFormat (Legacy)

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class Demo {
    public static void main(String args[]) throws ParseException {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        String str = formatter.format(date);
        System.out.print("Current date: " + str);
    }
}

ผลลัพธ์

05/11/20

วิธีที่ 2: ใช้ LocalDate.now() (Java 8+) - แนะนำ

import java.time.LocalDate;

public class CreateDate {
    public static void main(String args[]) {
        LocalDate date = LocalDate.now();
        System.out.println("Current Date: " + date);
    }
}

ผลลัพธ์

Current Date: 2020-11-05

วิธีที่ 3: ใช้ Calendar + SimpleDateFormat (Legacy)

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;

public class Test {
    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Calendar obj = Calendar.getInstance();
        String str = formatter.format(obj.getTime());
        System.out.println("Current Date: " + str);
    }
}

ผลลัพธ์

Current Date: 05/11/20

วิธีที่ 4: ใช้ java.sql.Date (สำหรับ Database)

public class CreateDate {
    public static void main(String[] args) {
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        System.out.println("Current Date: " + date);
    }
}

ผลลัพธ์

Current Date: 2020-11-05

วิธีที่ 5: ใช้ LocalDate.now(Clock) - ควบคุม Time Source

import java.time.Clock;
import java.time.LocalDate;
import java.time.ZoneId;

public class Test {
    public static void main(String[] args) {
        // ใช้ system clock ปกติ
        LocalDate today = LocalDate.now();
        
        // ใช้ UTC clock
        LocalDate todayUTC = LocalDate.now(Clock.systemUTC());
        
        // ใช้ Zone ที่กำหนด
        LocalDate todayBangkok = LocalDate.now(Clock.system(ZoneId.of("Asia/Bangkok")));
        
        System.out.println("System: " + today);
        System.out.println("UTC: " + todayUTC);
        System.out.println("Bangkok: " + todayBangkok);
    }
}

ตารางเปรียบเทียบ

วิธีคืนค่าThread-Safeใช้เมื่อไหร่
LocalDate.now()LocalDateใช่แนะนำ #1 วันที่อย่างเดียว
java.sql.Datejava.sql.Dateใช่JDBC, Database
Date + SimpleDateFormatStringไม่Legacy formatting
Calendar + SimpleDateFormatStringไม่Legacy

Best Practice

  • ใช้ LocalDate.now() สำหรับ application logic ทั่วไป
  • ใช้ java.sql.Date สำหรับ PreparedStatement.setDate()
  • หลีกเลี่ยง Date/Calendar/SimpleDateFormat ในโค้ดใหม่
  • สำหรับ Testing ใช้ Clock.fixed() หรือ Clock.offset() เพื่อควบคุมเวลา