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

แปลง String เป็น Date ใน Java ด้วย SimpleDateFormat

สมมติมี String วันที่ 2 รูปแบบ:

String date1 = "11/10/2018";
String date2 = "15-Mar-2019 21:11:35";

แปลง String เป็น Date ด้วย SimpleDateFormat:

SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date formattedDate1 = dateFormat1.parse(date1);
Date formattedDate2 = dateFormat2.parse(date2);

ตัวอย่างโค้ดเต็ม

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

public class Demo {
    public static void main(String[] args) throws Exception {
        String date1 = "11/10/2018";
        String date2 = "15-Mar-2019 21:11:35";
        
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        
        Date formattedDate1 = dateFormat1.parse(date1);
        Date formattedDate2 = dateFormat2.parse(date2);
        
        System.out.println(formattedDate1);
        System.out.println(formattedDate2);
    }
}

ผลลัพธ์

Thu Oct 11 00:00:00 UTC 2018
Fri Mar 15 21:11:35 UTC 2019

Pattern Letters สำคัญ:

  • yyyy - ปี 4 หลัก
  • MM - เดือน 2 หลัก (01-12)
  • dd - วัน 2 หลัก (01-31)
  • MMM - ชื่อเดือนย่อ (Jan, Feb, Mar...)
  • HH - ชั่วโมง 24 ชม. (00-23)
  • mm - นาที (00-59)
  • ss - วินาที (00-59)

แนะนำ (Java 8+):: ใช้ java.time.LocalDate, LocalDateTime, DateTimeFormatter แทน SimpleDateFormat (Thread-Safe, Immutable, API ทันสมัยกว่า)