Convert LocalDateTime into Date in Java

This example shows different ways of converting java.time.LocalDateTime into java.util.Date.

Convert LocalDateTime into Date Example

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * Class which shows different ways of converting java.time.LocalDateTime into java.util.Date. 
 *  
 * @author sourcecodeexamples.net
 *
 */
public class LocalDateTimeToDateConverter {

    public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
        return java.sql.Timestamp.valueOf(dateToConvert);
    }

    public static Date convertToDateViaInstant(LocalDateTime dateToConvert) {
        return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault())
            .toInstant());
    }
    
    public static void main(String[] args) {
  System.out.println(convertToDateViaSqlTimestamp(LocalDateTime.now()));
  System.out.println(convertToDateViaInstant(LocalDateTime.now()));
 }

}
Output:
2019-06-17 15:10:08.052
Mon Jun 17 15:10:08 IST 2019

Comments