Saurabh
Saurabh

Reputation: 2472

Get time from Instant and save in Cassandra

I have "eventTime" field in Cassandra table with data type "time". I am trying to save current UTC time but could not. I declared field in Java as -

private Long eventTime;

Tried several ways to get time from Instant but incorrect data is getting saved.

  1. Instant.now(clock).getLong(ChronoField.NANO_OF_SECOND)

Saved "00:00:00.093563694" in Cassandra

  1. LocalDateTime.ofInstant(Instant.now(clock), ZoneOffset.UTC).getHour()

Saved "00:00:00.000000001" in Cassandra

If I directly run insert query in CQL with string value as '16:15:09.049909' then it worked.

Shall I change data type to "text" and save time as String.

Upvotes: 1

Views: 2386

Answers (2)

Alex Ott
Alex Ott

Reputation: 87249

You can map Instant into Cassandra's timestamp if you use optional codecs from Java driver as described in documentation: https://docs.datastax.com/en/developer/java-driver/3.6/manual/custom_codecs/extras/#jdk-8

Add to pom.xml following:

<dependency>
  <groupId>com.datastax.cassandra</groupId>  
  <artifactId>cassandra-driver-extras</artifactId> 
  <version>3.6.0</version> 
 </dependency>

And register codec when creating Cluster object:

import com.datastax.driver.extras.codecs.jdk8.InstantCodec; 
import java.time.Instant; 
...
cluster.getConfiguration().getCodecRegistry()
     .register(InstantCodec.instance);

Upvotes: 1

Mandraenke
Mandraenke

Reputation: 3266

You want to save the current time to Cassandra?

LocalTime localTime = LocalTime.now();

You are extracting some information above in your code as ChronoField.NANO_OF_SECOND or .getHour(). Just use the local time entirely.

Upvotes: 0

Related Questions