แพ็กเกจ java.time ของ Java 8 มีคลาส LocalDateTime ใช้ดึงวันที่และเวลาท้องถิ่นปัจจุบัน รวมถึงฟิลด์อื่นๆ เช่น day-of-year, day-of-week, week-of-year
ขั้นตอนตั้งค่า LocalDateTime ลงคอลัมน์ Date/Time
- ได้ LocalDateTime object ด้วยเมธอด static
now() - แยก LocalDate และ LocalTime จาก LocalDateTime
- แปลงเป็น java.sql.Date และ java.sql.Time ด้วย
valueOf()
โค้ดสำคัญ
// 1. ได้ LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
// 2. แยก Date และ Time
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
// 3. แปลงเป็น SQL Date/Time
java.sql.Date date = java.sql.Date.valueOf(localDate);
java.sql.Time time = java.sql.Time.valueOf(localTime);
ตัวอย่างโค้ดเต็ม (Insert ลงตาราง dispatches)
import java.sql.*;
import java.time.LocalDateTime;
public class SettingLocalDate {
public static void main(String args[]) throws SQLException {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// ได้วันที่เวลาปัจจุบัน
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.toString());
// แปลงเป็น SQL Date/Time
java.sql.Date date = java.sql.Date.valueOf(localDateTime.toLocalDate());
java.sql.Time time = java.sql.Time.valueOf(localDateTime.toLocalTime());
// Insert
String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "Watch");
pstmt.setString(2, "Rajan");
pstmt.setDate(3, date);
pstmt.setObject(4, time);
pstmt.setInt(5, 4000);
pstmt.setString(6, "Chennai");
pstmt.execute();
System.out.println("Rows inserted ....");
// Query แสดงผล
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from dispatches");
while (rs.next()) {
System.out.println("Product: " + rs.getString("ProductName"));
System.out.println("Customer: " + rs.getString("CustomerName"));
System.out.println("Date: " + rs.getDate("DispatchDate"));
System.out.println("Time: " + rs.getTime("DeliveryTime"));
System.out.println("Location: " + rs.getString("Location"));
System.out.println();
}
}
}
ผลลัพธ์
Connection established......
2019-05-14T15:48:42.457
Rows inserted ....
Product: Watch
Customer: Rajan
Date: 2019-05-14
Time: 15:48:42
Location: Chennai
ข้อดีของ java.time
- Thread-safe และ immutable
- API ชัดเจน แยก Date/Time/DateTime ชัดเจน
- รองรับ Time Zone และ Formatting ได้ดี