Chuyển đổi LocalDate sang Timestamp trong Java

Trong Java, lớp LocalDate biểu diễn ngày tháng không chứa thông tin thời gian. Để chuyển đổi sang timestamp (dưới dạng mili giây hoặc giây), cần kết hợp với phần thời gian, thường mặc định là 00:00:00 đầu ngày.

Cách 1: Sử dụng atStartOfDay() và toEpochSecond()

Phương thức atStartOfDay() chuyển LocalDate thành LocalDateTime với thời gian bắt đầu ngày, sau đó dùng toEpochSecond() để lấy timestamp giây.

import java.time.*;

class DateConverter {
    public static void main(String[] args) {
        LocalDate ngayMau = LocalDate.of(2023, 11, 15);
        ZoneId muiGio = ZoneId.of("Asia/Ho_Chi_Minh");
        
        LocalDateTime dateTime = ngayMau.atStartOfDay();
        long timestampGiay = dateTime.toEpochSecond(muiGio.getRules().getOffset(dateTime));
        
        Instant thoiDiem = dateTime.atZone(muiGio).toInstant();
        long timestampMili = thoiDiem.toEpochMilli();
        
        System.out.println("Timestamp (giây): " + timestampGiay);
        System.out.println("Timestamp (mili giây): " + timestampMili);
    }
}

Cách 2: Sử dụng atStartOfDay(ZoneId)

Phương thức atStartOfDay(ZoneId) trực tiếp tạo đối tượng ZonedDateTime từ ngày và múi giờ.

import java.time.*;

class TimestampGenerator {
    public static void main(String[] args) {
        LocalDate ngayHienTai = LocalDate.now();
        ZoneId muiGio = ZoneId.systemDefault();
        
        ZonedDateTime zonedDT = ngayHienTai.atStartOfDay(muiGio);
        long ketQua = zonedDT.toInstant().toEpochMilli();
        
        System.out.println("Timestamp mili giây: " + ketQua);
    }
}

Cách 3: Chỉ định thời gian tùy chỉnh

Sử dụng LocalDateTime.of() để thiết lập thời gian cụ thể khi chuyển đổi.

import java.time.*;

class CustomTimeConverter {
    public static void main(String[] args) {
        LocalDate ngay = LocalDate.parse("2023-05-20");
        ZoneId muiGio = ZoneId.of("UTC");
        LocalTime gio = LocalTime.of(8, 30);
        
        LocalDateTime dateTimeCustom = LocalDateTime.of(ngay, gio);
        long timestamp = dateTimeCustom.atZone(muiGio).toInstant().toEpochMilli();
        
        System.out.println("Timestamp tùy chỉnh: " + timestamp);
    }
}

Lưu ý quan trọng

  • Timestamp luôn tính theo UTC, cần xác định rõ múi giờ khi chuyển đổi
  • Độ chính xác: 1 giây = 1000 mili giây
  • Nên sử dụng atStartOfDay() khi cần thời điểm bắt đầu ngày
  • Kiểm tra quy tắc múi giờ khi xử lý dữ liệu đa quốc gia

Thẻ: Java LocalDate Timestamp timezone DateTimeAPI

Đăng vào ngày 24 tháng 7 lúc 15:58