LocalDateTime to java.sql.Date in java 8?

后端 未结 3 1703

How to convert LocalDateTime to java.sql.Date in java-8?

My search on internet mostly give me Timestamp related code or

3条回答
  •  青春惊慌失措
    2020-11-30 09:21

    It is possible to convert from LocalDateTime to java.sql.date while retaining the time part without havng to make assumptions about the time-zone by using java.util.Date as an intermediary:

    LocalDateTime dateValue = // your LocalDateTime
    java.util.Date utilDate;
    String dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
    DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern(dateFormat);
    SimpleDateFormat sdf1 = new SimpleDateFormat(dateFormat);
    try {
        utilDate = sdf1.parse(dateValue.format(dtf1));
    } catch (ParseException e) {
        utilDate = null; // handle the exception
    }
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    

提交回复
热议问题