Search code examples
javadatecassandradatastaxlocaldate

convert java.util.Date to datastax's LocalDate


I'm trying to convert a date in yyyy-MM-dd String format to datastax's LocalDate. I'm using following code to do that.

private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

public static LocalDate getDate(String date) throws ParseException {
    Date d = DATE_FORMAT.parse(date);
    return LocalDate.fromMillisSinceEpoch(d.getTime());
}

When I tested this method I'm not getting expected results.

public static void main(String[] args) throws ParseException {
    System.out.println(getDate("2017-11-22"));
}
// Actual Output:
2017-11-21
// Excpected Output:
2017-11-22

Is there anything I'm missing here?


Solution

  • Something like:

    public static LocalDate convertDate(final String date) {
        String[] arr = date.split("-");
        if (arr.length != 3)
            return null;
        return LocalDate.fromYearMonthDay(Integer.parseInt(arr[0]),
                Integer.parseInt(arr[1]),
                Integer.parseInt(arr[2]));
    }