简体   繁体   中英

How can we convert com.datastax.driver.core.LocalDate to java.util.Date?

I am working with dates.

Datastax's CQL cassandra API Row.getDate() returns a com.datastax.driver.core.LocalDate .

I want to convert the com.datastax.driver.core.LocalDate object returned by the API to java.util.Date . How can I do that?

The LocalDate.getMillisSinceEpoch() Javadoc says Returns the number of milliseconds since January 1st, 1970 GMT. And, the Date(long) constructor Javadoc says Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. So, given a LocalDate ld you should be able to do something like

Date d = new Date(ld.getMillisSinceEpoch());

As the other answer mentions either you can use

Date d = new Date(row.getDate().getMillisSinceEpoch());

or you can use java.sql.Date.valueOf

Date d = java.sql.Date.valueOf(row.getDate().getString());

Instead of using row.getDate I personally use row.getTimestamp which returns Date object itself.

Date d = row.getTimestamp();

you can follow below steps, to convert datastax LocalDate to Date:

  1. create LocateDate using Year, Month and Date from datastax LocalDate
    datstax.Localdate dt = somevalue
    java.time.LocalDate ld = java.time.LocalDate.of(dt.getYear(), dt.getMonth(), dt.getDay())
  2. format above LocalDate then you will get String type date
    String dtt = ld.format(DateTimeFormater.ofPattern("dd/MM/yyyy"))
  3. then convert using SimpleDateFormat
    Date tt = new SimpleDateFormat("dd/MM/yyyy").parse(dtt)

Enjoy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM